Skip to main content

Command Palette

Search for a command to run...

Easily removing a specific item from an Array in JavaScript

Updated
1 min read

Let's say we have an array of numbers:

let values = [3, 6, 12];
console.log(values); // Output: [3, 6, 12]

If we wanted to remove the number '6' from this array we could use the following JavaScript code to achieve this:

const target = 6; 
const index = values.indexOf(target);

// if not -1 we found a match
if (index !== -1) { 
  // splice(start, deleteCount)
  values.splice(index, 1); 
}

console.log(values); // Output: [3, 12]

We get the index to find the target position usingindexOf(). This method returns the first occurrence of the designated element's index, or -1 if the element doesn't exist.

We then check if the element exists within the array. If it does, we implement splice() to erase it. The splice() method modifies the array by removing or replacing existing elements.

To replace instead you can use:

const target = 6; 
const index = values.indexOf(target);

if (index !== -1) { 
  // splice(start, deleteCount, item0)
  values.splice(index, 1, 7); 
}

console.log(values); // Output: [3, 7, 12]
A

Very informative

1
C

thank you, i am trying to make bite sized tips for developers, glad you liked it