How to add or remove value from javascript array

By | November 14, 2019
Spread the love

JavaScript is the world’s most popular programming language. JavaScript is the programming language of the Web.

JavaScript arrays are used to store multiple values in a single variable. An array is a special variable, which can hold more than one value at a time. Using an array literal is the easiest way to create a JavaScript Array.

var array_name = [item1item2, …];

JavaScript arrays allow you to group values and iterate over them. You can add and remove array elements in different ways.

Removing Elements from End of a JavaScript Array

var ar = [1, 2, 3, 4, 5, 6];
ar.pop(); // returns 6
console.log( ar ); // [1, 2, 3, 4, 5]

Removing Elements from Beginning of a JavaScript Array

var ar = ['zero', 'one', 'two', 'three'];
ar.shift(); // returns "zero"
console.log( ar ); // ["one", "two", "three"]

Removing Elements from Middle of a JavaScript Array

function arrayRemove(arr, value) {
   return arr.filter(function(ele){
       return ele != value;
   });
}

var result = arrayRemove(array, 6);
// result = [1, 2, 3, 4, 5, 7, 8, 9, 0]