How do I delete an item from an array in JavaScript?

What is the method for removing a particular value from an array? For example:

array.remove(value); 

Limitations: I must use core JavaScript. No frameworks can be utilized.

1 Like

To remove a specific value from an array using only core JavaScript functions, you can leverage the filter method. This provides a clean and efficient solution:

let array = [1, 2, 3, 4, 5, 3];
let valueToRemove = 3;

array = array.filter(item => item !== valueToRemove);

console.log(array); // Output: [1, 2, 4, 5]

Explanation:

  • filter: This array method creates a new array with elements that pass the condition you specify.
  • Condition: We set it to eliminate any array elements equal to valueToRemove.

This method doesn’t mutably change the original array but rather returns a new array with the specified value removed. It’s direct, easy to read, and makes the code elegant and efficient.

Hey there! Need a pure JavaScript way to remove a value from an array? You got it! Let’s make it straightforward without using filter. You can use splice along with indexOf for mutating the array in place:

let array = [1, 2, 3, 4, 5, 3];
let valueToRemove = 3;

let index = array.indexOf(valueToRemove);
while (index !== -1) {
  array.splice(index, 1);
  index = array.indexOf(valueToRemove);
}

console.log(array); // Output: [1, 2, 4, 5]

This approach modifies the original array directly. Give it a try and let me know if it does the trick!

1 Like