Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array of objects by sub array of values

Here is what I am trying to do:

movies = [{'title': 'a', 'genres': ['Romance', 'Comedy']}, 
          {'title': 'b', 'genres': ['Drama', 'Comedy']}, 
          {'title': 'c', 'genres': ['Action', 'Adventure']}]

filters = ['Romance', 'Drama']

Desired contents of filtered array:

[{'title': 'a', 'genres': ['Romance', 'Comedy']}, 
 {'title': 'b', 'genres': ['Drama', 'Comedy']}]

The issue is that I am not sure how to filter an array given another array of values. If 'filters' was just a single string, then I could just do:

movies.filter(x => x.genres.includes(filters))

But this obviously won't work if filters is an array of values.

Any help is much appreciated.

like image 335
yobogoya Avatar asked Feb 26 '18 21:02

yobogoya


People also ask

How do you filter nested array of objects?

How do you filter nested array of objects? The filter() method creates a new array with all elements that pass the test implemented by the provided function. Approach 1: This approach uses filter() method to filter the nested object in JavaScript.

How do you filter an array of objects by value?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.

How do you filter an array of objects by key?

You can use the Object. keys() function to convert the object's keys into an array, and accumulate the filtered keys into a new object using the reduce() function as shown below. const obj = { firstName: 'Jean-Luc', lastName: 'Picard', age: 59 }; // { firstName: 'Jean-Luc', lastName: 'Picard' } Object.

Can we apply filter method to an object?

JavaScript's Objects are not iterable like arrays or strings, so we can't make use of the filter() method directly on an Object . filter() allows us to iterate through an array and returns only the items of that array that fit certain criteria, into a new array.


1 Answers

You're very close. It looks like what you need is the array .some method. That method will return true if it's callback is true for any item, so what you need is for "some" genre to be included in the filter list:

movies = [{
    'title': 'a',
    'genres': ['Romance', 'Comedy']
  },
  {
    'title': 'b',
    'genres': ['Drama', 'Comedy']
  },
  {
    'title': 'c',
    'genres': ['Action', 'Adventure']
  }
]

filters = ['Romance', 'Drama']

//[{'title': 'a', 'genres': ['Romance', 'Comedy']}, 
// {'title': 'b', 'genres': ['Drama', 'Comedy']}]

console.log(movies.filter(x => x.genres.some(g => filters.includes(g))))
like image 184
CRice Avatar answered Oct 13 '22 21:10

CRice