Add/Remove item to/from Array  in Javascript

Add/Remove item to/from Array in Javascript

add/remove items from start/end of an array

In a simple definition, Javascript arrays are used to store multiple values in a single variable, which means, it can hold more than one value at a time.

For instance, if you have a list of items (a list of car names), storing the cars in a single variable could look like this:

let car1 = "BMW";
let car2 = "Ford";
let car3 = "Tesla";

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name and you can access the values by referring to an index number. For example,

let cars = ["BWM", "Ford", "Tesla"];

In the following, I am going to explain all methods by the group in order to make things easier to remember.

push()

This method add one or more elements to the end of the array and returns the new length of the array. For example,

const cars = ["BMW","Ford","Tesla"];
console.log(cars.push("Honda")): //output: 4
console.log(cars);  //output: '["BMW","Ford", "Tesla", "Honda"]'

pop()

This method removes the last element from the end of the array and returns that element.

const cars = ["BMW","Ford","Tesla"];
cars.pop();
console.log(cars);  //output: '["BMW","Ford"]'

Shift()

This method removes the first element from an array and returns that element.

const cars = ["BMW","Ford","Tesla"];
cars.shift();
console.log(cars);  //output: '["Ford","Tesla"]'

unshift()

This method adds one or more elements to the beginning of an array and returns the new length of the array

const cars = ["BMW","Ford","Tesla"];
console.log(cars.unshift("Honda")): //output: 4
console.log(cars);  //output: '["Honda", "BMW", "Ford", "Tesla"]'

slice()

This method returns a new array with specified start too end elements.

const cars = ["BMW","Ford","Tesla"];
const sliced = cars.slice(2,3);
console.log(slicked): //output: ["Tesla"];
console.log(cars): //output: '["BMW","Ford","Tesla"]'

concat()

This method is used to merge two or more arrays and returns a new array, without changing the existing arrays.

const car1 = ["BMW","Ford","Tesla"];
const car2 = ["Toyota", "Honda"];
const cars = car1.concat(car2);
console.log(cars); //output: '["BMW", "Ford", "Tesla", "Toyota", "Honda"]';
console.log(car1);//output: '["BMW","Ford","Tesla"]';
console.log(car2);//output: '["Toyota", "Honda"]';