Sometimes we might be working with an array of objects with unique IDs that allow each of them to be uniquely identified among other objects.
For example:
const arr = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Peter' },
{ id: 3, name: 'Kate' },
];
What if we want to remove an object that has a particular ID from the array? We’re going to learn multiple ways of doing so in this article.
1. Array
findIndex()
and splice()
methods
To remove an element from an array by ID in JavaScript, use the findIndex()
method to find the index of the object with the ID in the array. Then call the splice(index, 1)
method on the array to remove the object from the array.
function removeObjectWithId(arr, id) {
const objWithIdIndex = arr.findIndex((obj) => obj.id === id);
if (objWithIdIndex > -1) {
arr.splice(objWithIdIndex, 1);
}
return arr;
}
const arr = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Kate' },
{ id: 3, name: 'Peter' },
];
removeObjectWithId(arr, 2);
// [ { id: 1, name: 'John' }, { id: 3, name: 'Peter' } ]
console.log(arr);
The Array
findIndex()
method returns the index of the first element in an array that passes a test specified by a callback function.
const arr = [9, 8, 7, 6, 5];
const index = arr.findIndex((num) => num === 7);
console.log(index); // 2
We specify a test that an object in that array will pass only if it has an ID equal to the specified ID. This makes findIndex()
return the index of the object with that ID.
The Array
splice()
method changes the contents of an array by removing existing elements while adding new ones simultaneously.
const arr1 = ['a', 'b', 'c'];
// Removing elements
arr1.splice(1, 2);
console.log(arr1); // [ 'a' ]
// Removing and adding new elements
const arr2 = ['a', 'b', 'c'];
arr2.splice(1, 2, 'd', 'e');
console.log(arr2); // [ 'a', 'd', 'e' ]
This method takes three arguments:
start
– the index at which to start changing the array.deleteCount
– the number of elements to remove fromstart
item1, item2, ...
– a variable number of elements to add to the array, beginning fromstart
.
We specify a deleteCount
of 1
and a start
of the target index to make splice()
remove just the object with that index from the array. We didn’t specify any more arguments, so nothing is added to the array.
If no object passes the specified test, findIndex()
will return -1
. Because of this, we add an if
check to ensure that the index is 0
or greater.
Without this if
check, splice()
will be called with -1
as its first argument, and will remove the last element of the array, when there’s actually no element with the ID in the array:
const arr = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Kate' },
{ id: 3, name: 'Peter' },
];
// No such element with ID of 9
const objWithIdIndex = arr.findIndex((obj) => obj.id === 9);
console.log(objWithIdIndex); // -1
// ❌ No if check
arr.splice(objWithIdIndex, 1); // ❌ Removes last element!
// [ { id: 1, name: 'John' }, { id: 2, name: 'Kate' } ]
console.log(arr);
Avoid side effects
The Array
splice()
method mutates the passed array. This introduces a side effect into our removeObjectWithId()
function. To avoid modifying the passed array and create a pure function, make a copy of the array and call splice()
on the copy, instead of the original
function removeObjectWithId(arr, id) {
// Making a copy with the Array from() method
const arrCopy = Array.from(arr);
const objWithIdIndex = arrCopy.findIndex((obj) => obj.id === id);
arrCopy.splice(objWithIdIndex, 1);
return arrCopy;
}
const arr = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Kate' },
{ id: 3, name: 'Peter' },
];
const newArr = removeObjectWithId(arr, 2);
// [ { id: 1, name: 'John' }, { id: 3, name: 'Peter' } ]
console.log(newArr);
// original not modified
/**
[
{ id: 1, name: 'John' },
{ id: 2, name: 'Kate' },
{ id: 3, name: 'Peter' }
]
*/
console.log(arr);
Tip
Functions that don’t modify external state (i.e., pure functions) tend to be more predictable and easier to reason about. This makes it a good practice to limit the number of side effects in your programs.
2. Array
filter()
method
We can also remove an element from an array by ID with the filter()
method. We call filter()
on the array, passing a callback that returns true
for every element in that array apart from the object with the specified ID.
Example
function removeObjectWithId(arr, id) {
return arr.filter((obj) => obj.id !== id);
}
const arr = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Kate' },
{ id: 3, name: 'Peter' },
];
const newArr = removeObjectWithId(arr, 2);
// [ { id: 1, name: 'John' }, { id: 3, name: 'Peter' } ]
console.log(newArr);
// original not modified
/**
[
{ id: 1, name: 'John' },
{ id: 2, name: 'Kate' },
{ id: 3, name: 'Peter' }
]
*/
console.log(arr);
The Array
filter()
method creates a new array filled with elements that pass a test specified by a callback function. It does not modify the original array.
Example
const arr = [1, 2, 3, 4];
const filtered = arr.filter((num) => num > 2);
console.log(filtered); // [ 3, 4 ]
In our example, we set a test that an object in the array will pass only if its id
property is not equal to the specified ID. This ensures that the object with the specified ID is not included in the new array returned from filter()
.
11 Amazing New JavaScript Features in ES13
This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.
Notice that if u try to delete an element that doesn’t exist, findIndex returns -1, which means that instead of removing the (non-existing) element, splice removes the last element (-1) from the array.
Thank you for pointing that out. I’ve updated the article to first check if the result from
findIndex()
is greater than -1 before callingsplice()
.