Find a value within a nested array

Hey can anyone see what I’m doing wrong here?

function findHobbyists(hobbies, hobby) {
  const newArray = [];

  const hobbiesArray = Object.entries(hobbies);

  hobbiesArray.forEach(object => {
    object[1].includes(hobby);
    newArray.push(object[0]);
  });
  return newArray;
}

var hobbies = {
  John: ["Piano", "Puzzles", "Yoga"],
  Adam: ["Drama", "Fashion", "Pets"],
  Mary: ["Magic", "Pets", "Reading"]
};

console.log(findHobbyists(hobbies, "Yoga"));

Output should be John, but I get an array “1:John, 2:Adam, 3:Mary”

oh, Object.entries will only return keys… not sure whether I should be using Array.from instead?

You’re not doing anything to the result of that expression. Did you mean to do something with it? You will need to do that and use it in some way.

It returns an array of arrays where the first value is the key, and the second is the value of that prop in the object.

I think a lot of your confusion is a result of not knowing what Object.entries actually does,. and your choice of variable names.

in reply to steffan’s first comment: I’m adding the object to a new array?

The use of Object.entries is correct, there’s just an if check missing somewhere, see if you can find where it belongs.

What object are you talking about?

The correct way would be to use:

hobbiesArray.forEach(([name, hobbies]) => {


});

It is already used correctly, I tried the code with the if check in place and it worked.

Working !== right.

Objective is to be a better programmer.

1 Like
function findHobbyists(hobbies, hobby) {
  const newArray = [];

  const hobbiesArray = Object.entries(hobbies);

  hobbiesArray.forEach(object => {
    if (object[1].includes(hobby)) {
      newArray.push(object[0]);
    }
  });
  return newArray;
}

var hobbies = {
  John: ["Piano", "Puzzles", "Yoga"],
  Adam: ["Drama", "Fashion", "Pets"],
  Mary: ["Magic", "Pets", "Reading"]
};

console.log(findHobbyists(hobbies, "Yoga"));

it worked! thanks Steffan!

3 Likes

Applying what @kerafyrm02 said (using array destructuring), that part would look like this:

hobbiesArray.forEach(([name, hobbies]) => {
    if (hobbies.includes(hobby)) {
      newArray.push(name);
    }
  });

Indeed, much more readable.

Readability of code is probably one of the most important qualities a programmer can have.

1 Like