How to use reduce method In Javascript
The reduce() method is applied in this approach to iteratively build a new array that contains only the objects meeting the specified condition. The filter method is used to filter the items in the nested array, and the result is added to the accumulator array.
Example: This example shows the filtering of nested array using the key by using the reduce method.
Javascript
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.reduce((acc, obj) => { const filteredItems = obj.items.filter(item => item[keyToFilter] === valueToFilter); if (filteredItems.length > 0) { acc.push({ ...obj, items: filteredItems }); } return acc; }, []); console.log(JSON.stringify(filteredData, null , 2)); |
Output
[ { "id": 2, "items": [ { "name": "item3" } ] } ]
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