This post will describe the methods to find and remove objects in an array based on a key value in JavaScript
How to Find and Remove Objects in an Array Based on a Key Value in JavaScript?
To find and remove objects in an array, use the following methods:
Method 1: Find and Remove Objects in an Array Based on a Key-Value Using splice() Method With findIndex() Method
To find and remove the objects from an array, use the “splice()” method with the “findIndex()” method of the Array object. splice() method is utilized for adding and removing elements from an array, and the findIndex() method is an iterative method that offers a callback function to iterate the elements. This method outputs the index of the particular element.
Syntax
For finding the index of an element in an array, use the below-given syntax:
For removing an element from an array, use the given syntax of the splice() method:
In the above syntax:
- “index” is the position of the specified element to remove.
- “deleteCount” is the total number of elements to be deleted.
Example
Here, first, we will create an array of objects:
{name: 'Carl', id: 5},
{name: 'Aliice', id: 3},
{name: 'Alice', id: 1}];
Call the “findIndex()” method to find the object based on the key (id) and value (3) and store it in a variable “indexOfObject”:
return object.id === 3;
});
Then, print the index of the object:
Now, for removing that object from an array, call the “splice()” method by passing the index of the object and the count “1” that indicates only one element of an array will be removed:
Finally, print the array on the console:
The output displays the index of the specified object that is “2” and removes that object from an array successfully:
Method 2: Find and Remove Objects in an Array Based on a Key-Value Using filter() Method
Use the “filter()” method to find and remove the objects in an array. filter() method creates a new array containing elements that fulfill the specified criteria.
Syntax
Follow the given syntax for using the “filter()” method:
Example
Call the filter() method to filter out the elements of an array whose id is not equal to “3”:
return object.id !== 3;
});
Print the resultant array on the console:
Output
That’s all about finding and eliminating objects in an array based on the key value in JavaScript.
Conclusion
To find and remove objects in an array, use the “splice()” method with the “findIndex()” method or the “filter()” method. filter() method filters out the elements that fulfill the given criteria. While the findIndex() method finds out the element’s index, and the splice() method removes it from an array. In this post, we described the methods to find and remove objects in an array based on a key value in JavaScript.