Remove the last/first element from an array in Javascript

Remove the last/first element from an array in Javascript

In JavaScript, there are several ways to remove the last and first elements from an array. I

Here are some commonly used methods:

Removing the Last Element:

Array.pop() method: This method removes the last element from an array and returns it.

  •   let myArray = [1, 2, 3, 4, 5];
      let lastElement = myArray.pop(); // Removes 5 from the array
      console.log(myArray); // [1, 2, 3, 4]
      console.log(lastElement); // 5
    

    Array.slice() method: You can use the slice() method to create a new array without the last element

      let myArray = [1, 2, 3, 4, 5];
      let newArray = myArray.slice(0, -1); // Creates a new array without the last element
      console.log(newArray); // [1, 2, 3, 4]
    

    I had used Array.splice() method on our recently updated blog post of Valid Parenthesis (Check the alternative approach code)

Removing the First Element:

Array.shift() method: This method removes the first element from an array and returns it.

let myArray = [1, 2, 3, 4, 5];
let firstElement = myArray.shift(); // Removes 1 from the array
console.log(myArray); // [2, 3, 4, 5]
console.log(firstElement); // 1

Array.slice() method: You can use the slice() method to create a new array without the first element.

let myArray = [1, 2, 3, 4, 5];
let newArray = myArray.slice(1); // Creates a new array without the first element
console.log(newArray); // [2, 3, 4, 5]

Keep in mind that slice() creates a shallow copy, so it doesn't clone nested objects within the array.

If you have nested objects or arrays and want a deep copy, you'll need to implement a custom deep cloning function, which may have its time complexity considerations depending on the implementation.

Did you find this article valuable?

Support Dorothi Viki by becoming a sponsor. Any amount is appreciated!