Languages
[Edit]
EN

JavaScript - remove specific array item by value or reference

6 points
Created by:
Root-ssh
152730

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(arrayItem);  // finds item index

if (itemIndex > -1) {
	array.splice(itemIndex, 1);  // removes item with found index
}

 

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 itemIndex = array.indexOf(item);
  	if (itemIndex > -1) {
        const removedItems = array.splice(itemIndex, 1);
      	if (removedItems.length > 0) {
        	return true;
        }
    }
  	return false;
};


// Usage example 1 (by values):

//    index:    0    1    2    3
const array1 = ['a', 'b', 'c', 'd'];

removeItem(array1, 'c');              // removed '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);             // removed Matt item that has index 2
console.log(JSON.stringify(array2));  // [{"name":"John","age":25},{"name":"Kate","age":23},{"name":"Ann","age":19}]

References

  1. JavaScript - remove specific array item by index 

Alternative titles

  1. JavaScript - remove specific item from array by value or reference
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join