EN
JavaScript - remove specific array item by value or reference
6
points
In this short article, we would like to show how to remove an item by value or reference from an array in JavaScript.
Quick solution:
const itemIndex = array.indexOf(itemValue); // finds item index
if (itemIndex !== -1) {
array.splice(itemIndex, 1); // removes found item
}
Practical example
In this section, you can find 2 cases for array items removing: by value and by reference.
// ONLINE-RUNNER:browser;
const removeItem = (array, item) => {
const index = array.indexOf(item);
if (index !== -1) {
array.splice(index, 1);
return true;
}
return false;
};
// Usage example 1 (by values):
// index: 0 1 2 3
const array1 = ['a', 'b', 'c', 'd'];
removeItem(array1, 'c'); // removes 'c' item that has index 2
console.log(JSON.stringify(array1)); // ['a','b','d']
// Usage example 2 (by references):
const john = {name: 'John', age: 25}; // index 0
const kate = {name: 'Kate', age: 23}; // index 1
const matt = {name: 'Matt', age: 17}; // index 2
const ann = {name: 'Ann', age: 19}; // index 3
const array2 = [john, kate, matt, ann];
removeItem(array2, matt); // removes Matt item that has index 2
console.log(JSON.stringify(array2)); // [{name:'John',age:25},{name:'Kate',age:23},{name:'Ann',age:19}]