How to use filter() with some() method In Javascript
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.
Syntax:
let newArray = originalArray.filter((element) => {
return !conditionArray.some((conditionElement) => condition);
});
Example: The below code uses the filter() with some() 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.filter((geek) =>
!objtoRemove.some((obj) =>
obj.id === geek.id))
);
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