JavaScript Array Methods

JavaScript Array Methods

Array:-

The array is used to store ordered collections. Like if you want to store HTML elements, goods list and users list then you use an array data structure.

let arr=[ ];

We store all the elements in an array with the help of an index. You can store any type of value in a JavaScript array like string, boolean or number.

Array Methods:-

Push:-

It will add an element in the array at the last position.

let arr = [1,3,4];
arr.push(5);
console.log(arr);

pop:-

It will extract the last element from the array.

let fruits=["apple", "orange", "pear"];

fruits.pop()

shift:-

It will extract the first element from an array.

let fruits = ['apple',"orange","Pear"];
fruits.shift();

unshift:-

Add an element to the beginning of the array.

let arr = [2,4,6];
arr.unshift(1);

toString:-

It converts an array to a string and it will return a comma-separated list of elements.

let arr = [1,2,3];
String(arr) === '1,2,3';

splice:-

The splice method works as a multi-talented player for the array it can insert, remove and replace elements in an array.

arr.splice(start,deleteCount,elem1,elem2);

this method modifies the original array

remove elements:-

let arr = [1,2,3];
arr.splice(1,1);//it starts from index 1 and remove 1 element

Replace the element:-

let arr = [1,2,3,4,5,6];
arr.splice(0,2,"I","am");//It remove 2 elements from index 0 and replace them with other elements.

Insert an element:-

For inserting the elements we just make the delete count 0(zero).

let arr = [1,2,3,4,5,6];
arr.splice(1,0,89);
console.log(arr);

Slice:-

It will copy the element from the original array and return a new array.

arr.slice(start,end);

the end index is not included.

let arr = [1,2,3,4,5,6];
let arr2 = arr.slice(1,3);
console.log(arr2);

Concat:-

With the help of this method, we can include value in our existing array, and it will return the new array. It accepts any number of arguments either array or values.let

arr = [1,2,3,4];
arr=arr.concat([9,0]);
console.log(arr);

indexOf:-

It returns the starting index of an element.

arr.indexOf(item);

includes:-

It checks if an element is present in the array or not.

let arr = [1,2,3,4];
console.log(arr.includes(2));

lastIndexOf:-

It returns the last index of an element.

Reverse:-

It reverses the order of array elements.

let arr = [1,2,3,4];
arr.reverse();
console.log(arr);

Split:-

It split a string into an array by the given delimiter.

let place = "kashipur,Moradabad,kanpur";
let arr = place.split(",");
for(const key of arr){
    console.log(`You live in ${key}`);
}

Join:-

It does the opposite work of the split method it creates the string of array elements.

let arr = ["Asia", "India", "UK", "USA"];
let str = arr.join(";");
console.log(str);

isArray:-

It checks if the value is an array or not.

let arr = [1,2,3];
console.log(Array.isArray(arr));