Javascript Adding and Removing Elements From An Array

Code Snippets Adding And Removing Elements From An Array
Share:

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));

///////////////////////////////////////////////////////

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger