About
In this code snippet, we’ll find out how to add/remove elements to/from an array in Javascript.
At some point you will probably have the need to add or remove some item from an array.
Here’s how you do it:
Code:
let numbers = [ 1, 5, 7, 9 ]; //Add element/////////////////////////////////////////// numbers.unshift(8); //Will add an element at the beginning of the array. numbers.push(8); //Will add an element at the end of the array. console.log(numbers); /////////////////////////////////////////////////////// //Remove element/////////////////////////////////////// console.log("Removed: " + numbers.shift()); //Will remove and return the first element of the array. console.log("Removed: " + numbers.pop()); //Will remove and return the last element of the array. console.log(numbers); /////////////////////////////////////////////////////// //Remove/add element at//////////////////////////////// console.log("Removed: " + numbers.splice(0, 1)); //Remove 1 element from index 0. console.log("Removed: " + numbers.splice(0, 2, 11, 12)); //Add 2 elements(11 and 12) at index 0. console.log(numbers); /////////////////////////////////////////////////////// //Join arrays.///////////////////////////////////////// let someMoreNumbers = [ 115, 555, 111 ]; console.log(numbers.concat(someMoreNumbers)); ///////////////////////////////////////////////////////