Find a value within a nested array

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

function locateEntertainmentFansByType(activitiesObj, activityType) {
  const enthusiastsArr = [];

  const activityEntriesArr = Object.entries(activitiesObj);

  activityEntriesArr.forEach(entry => {
    if (entry[1].includes(activityType)) {
      enthusiastsArr.push(entry[0]);
    }
  });

  return enthusiastsArr;
}

var activitiesObj = {
  Jack: ["Guitar", "Hiking", "Cycling"],
  Lisa: ["Pilates", "Dancing", "Reading"],
  Tom: ["Painting", "Drawing", "Hiking"]
};

console.log(locateEntertainmentFansByType(activitiesObj, "Cycling"));

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 locateEntertainmentFansByType(activities, activityType) {
  const enthusiasts = [];

  const activitiesArray = Object.entries(activities);

  activitiesArray.forEach(activity => {
    if (activity[1].includes(activityType)) {
      enthusiasts.push(activity[0]);
    }
  });

  return enthusiasts;
}

var activitiesObj = {
  Jack: ["Guitar", "Hiking", "Cycling"],
  Lisa: ["Pilates", "Dancing", "Reading"],
  Tom: ["Painting", "Drawing", "Hiking"]
};

console.log(locateEntertainmentFansByType(activitiesObj, "Hiking"));

it worked! thanks Steffan!

2 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