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.

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

Similar Reads

Using filter() with some() method

This approach uses the filter() method with the some() method to remove objects from each inner array based on the condition that their id should not match any id in the objtoRemove array....

Using filter() with includes() method

This approach uses the filter() with includes() method to remove objects whose id matches an id in the objtoRemove array....

Using filter( ) with findIndex() method

This approach uses the filter() with the findIndex() method to remove objects from the inner array where the id matches any id in the objToRemove array using the findIndex() method....

Using filter() with reduce() method

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....

Using filter() with Set for Efficient Removal

In this approach, we use a Set to store the IDs of the objects we want to remove for efficient look-up. We then use filter() to remove objects based on whether their IDs are present in the Set....