DEV Community

Cover image for Manipulating Arrays
Sai Pavan
Sai Pavan

Posted on • Edited on

Manipulating Arrays

🎯 With push()

The push() function is used to add data to the end of an array.

It can take one or more parameters as shown with an example:

{
    var arr1 = [1,2,3];
    arr1.push(4);
    var arr2 = [β€œStimpson”, β€œj” ,”cat”];
    arr1.push([β€œhappy” , β€œjoy”]);
}
Enter fullscreen mode Exit fullscreen mode

🎯 With pop()

The pop() function is the opposite of push() , which removes data from the end of an array.

Any type of data can be popped off from the array with an example:

{
    var threeArr = [1,4,6];
    var oneDown = threeArr.pop();
    console.log(oneDown);
    console.log(threeArr);
}
Enter fullscreen mode Exit fullscreen mode

🎯 With unshift()

The unshift() function can unshift elements from either the end or the beginning of the array

Example:

{
    var arr = [β€œStimpson”, β€œj” ,”cat”];
    arr.shift();
    arr.unshift(β€œhappy”);
    after shift, arr will have value [β€œj” ,”cat”], after unshift() the arr would have [β€œhappy”, β€œj” ,”cat”]
}
Enter fullscreen mode Exit fullscreen mode

🎯 With shift()

The shift() function can shift elements from either the end or the beginning of the array

Example:

{
    var arr = [β€œStimpson”, β€œj” ,”cat”];
    var removedFromarr = arr.shift();
    after shift, arr will have value [β€œj” ,”cat”], after shift() the arr would have [β€œhappy”, β€œj” ,”cat”]
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)