What is the best way to use JavaScript to remove an element from an array without using frameworks?

I need to remove a specific value from an array using only core JavaScript. Something like array.remove(value);—what’s the proper way to achieve a JavaScript remove element from array operation?

I’ve worked with arrays quite a bit, and one of the most reliable ways to remove an element from an array is using Array.prototype.splice(). It directly modifies the array by removing or replacing elements. Here’s a quick example:

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

let index = array.indexOf(valueToRemove);
if (index !== -1) {
    array.splice(index, 1);  // Removes the element at the found index
}

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

In this example, you first find the index of the element you want to remove. If it exists, you use splice() to remove it. If it’s not in the array, indexOf() returns -1, and nothing happens. Pretty straightforward!

Great method Joe! If you’re looking for something that doesn’t modify the original array, a more functional approach would be using Array.prototype.filter(). This way, you can get a new array without the element you want to remove, keeping your original array intact.

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

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

console.log(newArray);  // [1, 2, 4, 5]

With filter(), you return a new array that includes all the elements except the one you’re trying to remove. This can be particularly useful if you don’t want to mutate the original array, which is often a good practice, especially in functional programming.

Nice, Devan! Another variation you might consider, if you’re okay with a slightly different approach, is combining indexOf() with splice(), but in a slightly altered way. You can mark the element as undefined before removing it. This could come in handy in specific scenarios.

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

let index = array.indexOf(valueToRemove);
if (index > -1) {
    array[index] = undefined;  // Mark it as undefined
    array.splice(index, 1);     // Remove the element
}

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

This method works similarly to the first one but adds an intermediate step where the element is first marked as undefined. After that, splice() cleans up the element. While this might not be necessary in all cases, it could be helpful in certain use cases where you need to track the removal process or mark an element as deleted before actually removing it.