Approach 3: Using forEach()
The forEach() method executes a provided function once for each array element.
Syntax:
array.forEach(callback(currentValue, index, array), thisArg);
Parameters:
- callback: A function that accepts up to three arguments. The forEach() method calls the callback function for each element in the array.
- currentValue: The value of 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 forEach() was called upon.
- thisArg (optional): Object to use as this when executing callback.
Example: The following code demonstrates the splice() method. In this example, we are using a for loop to iterate over the array. Inside the loop, we check if the ‘id’ property of the current element matches the value we want to remove. If it does, we use the splice() method to remove that element from the array. We also decrement the index variable to ensure that we don’t skip any elements. Finally, we log the updated array to the console.
Javascript
let arr = [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }, { id: 3, name: 'Bob' }, { id: 4, name: 'Alice' } ]; for (let i = 0; i < arr.length; i++) { if (arr[i].id === 2) { arr.splice(i, 1); i--; } } 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