How to usethe filter() method in Javascript
The filter() method is useful if you want to preserve the original array and create a new one without the element(s) you want to remove. The filter() method creates a new array with all the elements that pass the test implemented by the provided function.
Syntax:
array.filter(callback(element, index, array), thisArg);
Parameters:
- callback: A function that accepts up to three arguments. The filter() method calls the callback function for each element in the array and returns a new array with all the elements for which the callback function returns “true”.
- element: The current element being processed in the array.
- index (optional): The index of the current element being processed in the array.
- array (optional): The array filter() was called upon.
- thisArg (optional): Object to use as this when executing callback.
Example: In this example, The code removes the object with id: 2 from the array arr using the filter() method and logs the updated array.
Javascript
let arr = [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }, { id: 3, name: 'Bob' }, { id: 4, name: 'Alice' } ]; arr = arr.filter(item => item.id !== 2); console.log(arr); |
[ { id: 1, name: 'John' }, { id: 3, name: 'Bob' }, { id: 4, name: 'Alice' } ]
Remove Array Element Based on Object Property in JavaScript
In JavaScript, we often work with arrays of objects. Sometimes we may need to remove an element from an array based on a specific property of the object it contains. For example, we may want to remove all objects from an array where the value of the id property matches a certain value. In this article, we will discuss various approaches to achieve this in JavaScript.
There are several methods that can be used to remove array elements based on object property:
Table of Content
- Using the filter() method
- Using splice() method
- Using forEach()
- Using reduce() method
Contact Us