How to usesplice() method in Javascript

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. 

Syntax:

array.splice(start, deleteCount, item1, ..., itemX);

Parameters:

  • start: The index at which the array is changed. If greater than the length of the array, the actual starting index will be set to the length of the array. If negative, it will begin that many elements from the end of the array.
  • deleteCount (optional): An integer indicating the number of old array elements to remove. If deleteCount is 0 or negative, no elements are removed.
  • item1, …itemX (optional): The elements to add to the array, beginning at the start index. If you don’t specify any elements, splice() will only remove elements from the array.

Example: The following code demonstrates the forEach() method. In this example, we are using the forEach() method to iterate over the array. Inside the callback function, 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. Since we are modifying the array while iterating over it, we need to use the index parameter to ensure that we remove the correct element. 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'
}
];
 
arr.forEach((item, index) => {
    if (item.id === 2) {
        arr.splice(index, 1);
    }
});
 
console.log(arr);


Output

[
  { 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

Similar Reads

Approach 1: Using the filter() method

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....

Approach 2: Using splice() method

...

Approach 3: Using forEach()

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place....

Approach 4: Using reduce() method

...