Easily removing a specific item from an Array in JavaScript

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]