* push(element) method is used to insert a new element & it will append at the end of the array.
var array = [1,2,3,4]; array.push(5); //array1 = [1,2,3,4,5] array.push(7); //array1 = [1,2,3,4,5,7] array.push(2); //array1 = [1,2,3,4,5,7,2]
Time complexity: O(1)
*To delete an element, we will use the pop() method. This will remove from the end. It will return the deleted element.
var array = [1,2,3,4]; array.pop(); //4 array = [1,2,3] array.pop(); //3 array = [1,2]
*Opposite to pop() method is shift(). shift() method will remove elements from the beginning of the array.
var array = [1,2,3,4]; array.shift(); //1 array = [2,3,4] array.shift(); //2 array = [3,4]
If we change the length value then implicitly elements are deleted from the array(from the last).
var array=[3,99,66,55,88]; array.length=2; console.log('array= '+array); //output:array=[3,99]
slice(startingIndex, endingIndex):
To return specific elements from an array, we use slice() method.
Here,
startIndex = will start from "zero"
Here,
startIndex = will start from "zero"
endIndex = will start from "one"
var array=[3,99,66,55,88]; console.log('array ='+array.slice(1,3)); //output: array=[99,66]
There are multiple ways, below are the 2 approaches :
1. By using the "=" operator. Please note, it works as a call by reference. Meaning changing values in one array will reflect in another array as well.
var array1 = [1,2,3,4], array2 = array1; array1 // [1,2,3,4] array2 // [1,2,3,4] array2[0] = 5; array1 // [5,2,3,4] array2 // [5,2,3,4]
var array1=[3,99,66,55,88]; var array2 = Array.from(array1); console.log('array2='+array2); //Output: [3,99,66,55,88] array2[0]=5; console.log('array1='+array1); //Output: [3,99,66,55,88] console.log('array2='+array2);//Output: [5,99,66,55,88]
Comments
Post a Comment