HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How can I remove a specific item from an array in JavaScript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arrayhowfromremovecanspecificitemjavascript

Problem

How do I remove a specific value from an array? Something like:
array.remove(value);


Constraints: I have to use core JavaScript. Frameworks are not allowed.

Solution

Find the index of the array element you want to remove using indexOf, and then remove that index with splice.

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



const array = [2, 5, 9];

console.log(array);

const index = array.indexOf(5);
if (index > -1) { // only splice array when item is found
array.splice(index, 1); // 2nd parameter means remove one item only
}

// array = [2, 9]
console.log(array);




The second parameter of splice is the number of elements to remove. Note that splice modifies the array in place and returns a new array containing the elements that have been removed.

For completeness, here are functions. The first function removes only a single occurrence (e.g., removing the first match of 5 from [2,5,9,1,5,8,5]), while the second function removes all occurrences:



function removeItemOnce(arr, value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}

function removeItemAll(arr, value) {
var i = 0;
while (i



In TypeScript, these functions can stay type-safe with a type parameter:
function removeItem(arr: Array, value: T): Array {
const index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
`

Context

Stack Overflow Q#5767325, score: 17015

Revisions (0)

No revisions yet.