How to Delete Multiple Values from a JavaScript Array?

Estimated read time 2 min read

You can delete multiple values from a JavaScript array using the splice() method. Here’s an example:

const myArray = [1, 2, 3, 4, 5];
myArray.splice(1, 2); // removes 2 elements starting at index 1
console.log(myArray); // [1, 4, 5]

In this example, we first define an array myArray with five elements. We then call the splice() method on the array, passing in two arguments: the starting index at which to begin deleting elements (in this case, index 1) and the number of elements to delete (in this case, 2). The splice() method modifies the original array in place, removing the specified elements and shifting any remaining elements to fill the gap.

The resulting array, myArray, contains the original array with the specified elements removed.

Note that you can remove multiple elements from different locations in the array by calling splice() multiple times. You can also insert new elements into the array by passing additional arguments to splice(). For example, to remove two elements starting at index 1 and insert a new element at that index, you could do the following:

const myArray = [1, 2, 3, 4, 5];
myArray.splice(1, 2, "new element"); // removes 2 elements starting at index 1 and inserts "new element"
console.log(myArray); // [1, "new element", 5]

In this example, we pass "new element" as an additional argument to splice(), which inserts the new element at index 1 and removes the two elements starting at that index. The resulting array, myArray, contains the original array with the specified elements removed and the new element inserted.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply