Skip to content
Advertisement

How to filter an array of complex object

I have an array of users and each user has a array of tags and I have an array of selected Tags What is the best way in ES6 to filter the users by selected tags

const users = [
  {
    username: "john",
    tags: [{id:1}, {id:3},{id:5},{id:7}]
  },
  {
    username: "becky",
    tags: [{id:1}, {id:7},{id:6}]
  },
  {
    username: "susy",
    tags: [{id:1}, {id:4},{id:5}]
  },
  {
    username: "tyson",
    tags: [{id:3},{id:5}]
  },
];

and my selected tags are

let tagIds = [7,5];

and I expect to receive a result as

users = [
  {
    username: "john",
    tags: [{id:1}, {id:3},{id:5},{id:7}]
  },
];

Advertisement

Answer

Filter the users, and then check that every id is found in the tags of the user by using Array.some():

const users = [{"username":"john","tags":[{"id":1},{"id":3},{"id":5},{"id":7}]},{"username":"becky","tags":[{"id":1},{"id":7},{"id":6}]},{"username":"susy","tags":[{"id":1},{"id":4},{"id":5}]},{"username":"tyson","tags":[{"id":3},{"id":5}]}];

const tagIds = [7,5];

const result = users.filter(({ tags }) => 
  tagIds.every(id => 
    tags.some(t => t.id === id)
  )
);

console.log(result);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement