How to use filter method In Javascript
The filter method is used to filter the main array based on a condition specified using the same method. The same method checks if at least one element in the nested array meets the given condition. This method directly filters the objects in the main array based on the specified key and value.
Example: This example shows the filtering of a nested array using the key by using the filter method.
Javascript
// data taken const data = [ { id: 1, items: [{ name: 'item1' }, { name: 'item2' }] }, { id: 2, items: [{ name: 'item3' }, { name: 'item4' }] }, { id: 3, items: [{ name: 'item5' }, { name: 'item6' }] } ]; const keyToFilter = 'name' ; const valueToFilter = 'item3' ; const filteredData = data.filter(obj => obj.items.some(item => item[keyToFilter] === valueToFilter)); console.log(JSON.stringify(filteredData, null , 2)); |
Output
[ { "id": 2, "items": [ { "name": "item3" }, { "name": "item4" } ] } ]
How to filter Nested Array using Key in JavaScript ?
Filtering a nested array in JavaScript involves the process of selectively extracting elements from an array of objects, where each object contains another array. We will discuss how can we filter Nested Array using the key in JavaScript.
Filtering a nested array based on a key in JavaScript can be done using various methods:
Table of Content
- Using filter method
- Using reduce method
- Using map and filter
Contact Us