JS: Array.prototype.splice
splice
is the general way to add or remove elements of a array, at any index position.
arrayX.splice(start)
-
Delete all tail elements starting at index start, including it.
Return a Array of removed elements, or empty array if none removed.
// clear all elements const xx = [3, 4, 5]; xx.splice(0); console.log(xx.length === 0);
// remove rest starting at index 2 const xx = [0, 1, 2, 3, 4, 5]; const yy = xx.splice(2); // array is modified console.log(JSON.stringify(xx) === "[0,1]"); // removed items console.log(JSON.stringify(yy) === "[2,3,4,5]");
arrayX.splice(start, n)
-
Delete n items.
const xx = [0, 1, 2, 3, 4, 5]; // remove 3 elements, starting at index 2 const yy = xx.splice(2, 3); // the new value console.log(JSON.stringify(xx) === "[0,1,5]"); // removed items console.log(JSON.stringify(yy) === "[2,3,4]");
arrayX.splice(start, n, new1, new2, etc)
-
Add new items.
// example of adding element to array const xx = [0, 1, 2, 3, 4, 5]; // add "b" before index 2 const yy = xx.splice(2, 0, "b"); console.log(JSON.stringify(xx) === `[0,1,"b",2,3,4,5]`); // removed items console.log(JSON.stringify(yy) === "[]");
const xx = [0, 1, 2, 3]; // insert a array as item xx.splice(2, 0, [88, 99]); console.log(JSON.stringify(xx) === "[0,1,[88,99],2,3]");
💡 TIP: use Spread Operator to avoid nested array.
const xx = [0, 1, 2, 3]; // a function that returns array const ff = () => [8, 9]; // insert a array as items xx.splice(2, 0, ...ff()); console.log(JSON.stringify(xx) === "[0,1,8,9,2,3]");
Replace a Slice (Delete and Add)
const xx = [0, 1, 2, 3, 4, 5]; /* example of array splice, remove some, add some start at index 2, removed 3 items, add "a" */ const yy = xx.splice(2, 3, "a"); // the new value console.log( JSON.stringify( xx ) === `[0,1,"a",5]` ); // removed items console.log( JSON.stringify( yy ) === "[2,3,4]");