In this part, I will cover most important instance methods of JS arrays.
Add elements to Array
Array.prototype.push()
it adds element at the end of array and returns new length of array.
const arr = [1,2,3];
console.log(arr.push(5,6)); //output:- 5
console.log(arr); //output:- [1,2,3,5,6]
Array.prototype.unshift()
it adds element at the starting of array and returns new length of array.
const arr = [1,2,3];
console.log(arr.unshift(5)); //output:- 4
console.log(arr); //output:- [5,1,2,3]
Array.prototype.concat()
concat method concatenates the array with given arrays or values. It doesn’t modify the original array just returns the concatenated array.
const arr1 = [1,2,3];
const arr2 = [4,5,6];
const arr3 = arr1.concat(arr2);
console.log(arr3); output:- [1,2,3,4,5,6]
console.log(arr1); output:- [1,2,3]
concat() is very handy property if you wanna modify an array without changing original array.
Delete elements of array
Array.prototype.pop()
it deletes one element at the end of array and returns new length of array.
const arr = [1,2,3];
console.log(arr.pop()); //output:- 2
console.log(arr); //output:- [1,2]
Array.prototype.shift()
it deletes one element at the end of array and returns new length of array.
const arr = [1,2,3];
console.log(arr.shift()); //output:- 2
console.log(arr); //output:- [2,3]
Array.proptype.slice()
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified. syntax - slice(start, end)
const arr= [1,2,3,4,5];
console.log(arr.slice(2,4)) //output:- [3,4]
console.log(arr.slice(2)) //output:- [3]
console.log(arr.slice(-2)) //output:- [4,5]
console.log(arr.slice()) //output:- [1,2,3,4,5]
Array.proptype.splice()
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. It return an array containing the deleted elements. syntax - splice(start, deleteCount, item1, item2, itemN)
const arr = [1,2,3,4,5,6];
console.log(arr.splice(2,3)) //output:- [3,4,5] deletes 3 elements after startindex=2
console.log(arr) //output:- [1,2,6] -modifies original array too
splice to add element in array
const arr = [1,2,3,4,5,6];
console.log(arr.splice(2,3,33,44)); //output:- [3,4,5]
console.log(arr); //- [1,2,33,44,6]