Languages
[Edit]
EN

JavaScript - remove specific array item by value or reference

6 points
Created by:
Root-ssh
116210

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

// 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 removedItems[0];
        }
    }
  	return undefined;
};


// Usage example 1:

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

removeItem(array1, 'c'); // removed 'c' item that has index 2
console.log(array1);     // a, b, d


// Usage example 2:

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