0

I have an array of objects named profiles: [{id: 0, subcategories: ['A', 'B', 'C']}, {id: 1, subcategories: ['A']}]

I have an array named tags: ['B']

I want to filter profiles, only keeping profiles that have a value in tags. In this case, profile with id = 0 would be saved.

This is what I have tried so far and it doesn't seem to be working:

      let filtered_profiles = profiles.filter((profile) =>
        tags.includes(profile.subcategories)
     );
1
  • 1
    let filtered_profiles = profiles.filter((profile) => profile.subcategories.some(sub => tags.includes(sub))); Commented Jul 15, 2021 at 16:04

1 Answer 1

0

This is my approach. If profiles subcategories includes at least one tag, push it into the result object.

let profiles = [{id: 0, subcategories: ['A', 'B', 'C']}, 
                     {id: 1, subcategories: ['A']}];

let tags = ['B'];
let result = [];

profiles.forEach(function (p){
let copied = false;
  tags.forEach(function (t) {
    if (p.subcategories.includes(t) && !copied) {
      result.push(p);
      copied = true;
    }
  })
});

console.log(result);

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.