0

could you help with these problem.

I need to filter the items in the array that contains certains activities in their object array. Heres is the code:

let userArray = [{
    name: "alonso",
    age:16,
    hobbies: [{activity:"videogames", id: 1}, {activity:"watch tv", id:2}]
  },
  {
    name: "aaron",
    age:19,
    hobbies: [{activity:"videogames", id:1}, {activity:"soccer", id:8}]
  },
  {
    name: "Luis",
    age:27,
    hobbies: [{activity:"code", id:3}, {activity:"soccer", id:8}]
}]

if "videogames" is passed by string the output expected is:

[{
   name: "alonso",
   age:16,
   hobbies: [{activity:"videogames", id: 1}, {activity:"watch tv", id:2}]
 },
 {
   name: "aaron",
   age:19,
   hobbies: [{activity:"videogames", id:1}, {activity:"soccer", id:8}]
}]
2
  • Use the Array.some() method in the filter callback function. Commented May 3, 2022 at 3:53
  • The norm on the site is for questions to show what's been tried. Consider that your filter should contain a find, like people.filter(person => person.hobbies.find(hobby => hobby.activity === someActivity)) Commented May 3, 2022 at 3:53

4 Answers 4

2

You can use Array.prototype.filter() combined with Array.prototype.some():

const userArray = [{name: 'alonso',age: 16,hobbies: [{ activity: 'videogames', id: 1 },{ activity: 'watch tv', id: 2 },],},{name: 'aaron',age: 19,hobbies: [{ activity: 'videogames', id: 1 },{ activity: 'soccer', id: 8 },],},{name: 'Luis',age: 27,hobbies: [{ activity: 'code', id: 3 },{ activity: 'soccer', id: 8 },],},]

const getUsersByActivity = (array, activity) =>  array.filter(
  user => user.hobbies.some(hobby => activity === hobby.activity)
)

const result = getUsersByActivity(userArray, 'videogames')
console.log(result)

Sign up to request clarification or add additional context in comments.

Comments

0
var users = [
{
    name: "aaron",
    age: 19,
    hobbies: [
      { activity: "videogames", id: 1 },
      { activity: "soccer", id: 8 },
    ],
  },
  {
    name: "Luis",
    age: 27,
    hobbies: [
      { activity: "code", id: 3 },
      { activity: "soccer", id: 8 },
    ],
  },
];

function getUsersBasedOnActivity(activity) {
  return users.filter((data) => {
    const hobbies = data.hobbies.map((hobby) => hobby.activity);
    return hobbies.includes(activity);
  });
}

console.log(getUsersBasedOnActivity('videogames'))

Comments

0

using array.filter you could filter out the objects that dont have the trait you are looking for userArray.filter(x => x.hobbies[0].activity === "videogames");

Comments

0
userArray.filter(user => {
  if(user.hobbies.some(hobby => hobby.activity == "videogames")){
  return user
  }
  })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.