Open In App

How to Remove Multiple Object from Nested Object Array ?

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Removing multiple objects from a nested object array in JavaScript involves traversing the array and filtering out the objects that meet certain criteria, such as having specific properties or values. This can be achieved using various array manipulation methods available in JavaScript.

Below are the approaches used to remove the multiple object from nested object arrays:

Approach 1: Using the filter() method

The filter() method creates a new array with all elements that pass the test implemented by the provided function. In this approach, we use filter() to iterate over the nested object array and return a new array that excludes the objects with IDs specified in the idsToRemove array.

Example: In this example, we have a nested object array representing a list of users, each with an ID and a name. We also have an array idsToRemove containing IDs of users we want to remove from the array. We use the filter() method to create a new array called filteredArray, which excludes the users with IDs present in the idsToRemove array.

Javascript




const nestedArray = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Alice' },
  { id: 3, name: 'Bob' },
  { id: 4, name: 'Eve' }
];
 
const idsToRemove = [2, 4];
 
const filteredArray = nestedArray.filter(item =>
    !idsToRemove.includes(item.id));
 
console.log(filteredArray);


Output

[ { id: 1, name: 'John' }, { id: 3, name: 'Bob' } ]

Approach 2: Using splice() method

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. In this approach, we traverse the nested object array in reverse order and use splice() to remove objects with IDs specified in the idsToRemove array directly from the array.

Example: In this example, we again have a nested object array representing a list of users. Instead of creating a new array, we modify the existing nestedArray in place. We traverse the array in reverse order to avoid index shifting issues when removing elements. For each element, if its ID matches any ID in the idsToRemove array, we use splice() to remove it from the array.

Javascript




const nestedArray = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Alice' },
  { id: 3, name: 'Bob' },
  { id: 4, name: 'Eve' }
];
 
const idsToRemove = [2, 4];
 
for (let i = nestedArray.length - 1; i >= 0; i--) {
  if (idsToRemove.includes(nestedArray[i].id)) {
    nestedArray.splice(i, 1);
  }
}
 
console.log(nestedArray);


Output

[ { id: 1, name: 'John' }, { id: 3, name: 'Bob' } ]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads