Removing / adding elements using splice

suggest change

The splice() method can be used to remove elements from an array. In this example, we remove the first 3 from the array.

const values = [1, 2, 3, 4, 5, 3];
const i = values.indexOf(3);
if (i >= 0) {
  values.splice(i, 1);
}
// [1, 2, 4, 5, 3]

The splice() method can also be used to add elements to an array. Insert at values.length to put numbers 6, 7, and 8 at the end. A start past the end is clamped to the length, so length + 1 happens to work, but it is not the end index.

const values = [1, 2, 4, 5, 3];
const i = values.length;
values.splice(i, 0, 6, 7, 8);
//[1, 2, 4, 5, 3, 6, 7, 8]

The first argument of the splice() method is the index at which to remove/insert elements. The second argument is the number of elements to remove. The third argument and onwards are the values to insert into the array.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents