How to use filter() with reduce() method In Javascript
This approach uses the filter() with reduce() method to remove objects from each inner array where the id matches an id in the objToRemove array.
Syntax:
let newArray = originalArray.map((elementArray) =>
elementArray.reduce((accumulator, element) => {
// condition
if (/* condition */) {
accumulator.push(element);
}
return accumulator;
}, [])
);
Example: The below code uses the filter() with reduce() method to remove multiple objects from a nested array of objects in JavaScript.
let arr =
[
[
{ id: 1, name: "Geek1" },
{ id: 2, name: "Geek2" },
],
[
{ id: 3, name: "Geek3" },
{ id: 4, name: "Geek4" },
],
];
let objtoRemove =
[
{ id: 2, name: "Geek2" },
{ id: 4, name: "Geek4" }
];
// removing objects using some function
let outputArr = arr.map((inArr) =>
inArr.reduce((acc, geek) => {
if (!objtoRemove.some((obj) =>
obj.id === geek.id))
{
acc.push(geek);
}
return acc;
}, [])
);
console.log("Before:", arr);
console.log("After:", outputArr);
Output
Before: [ [ { id: 1, name: 'Geek1' }, { id: 2, name: 'Geek2' } ], [ { id: 3, name: 'Geek3' }, { id: 4, name: 'Geek4' } ] ] After: [ [ { id: 1, name: 'Geek1' } ], [ { id: 3, name: 'Geek3' } ] ]
How to Remove Multiple Objects from Nested Array of Objects in JavaScript ?
A nested array of objects is an array of arrays that contain multiple objects as their elements. Removing multiple objects from the nested array of objects in JavaSript can be accomplished in different ways as listed below:
Table of Content
- Using filter() with some() method
- Using filter() with includes() method
- Using filter( ) with findIndex() method
- Using filter() with reduce() method