'Reduce length of an array by 1 [duplicate]

I have an array of images and I just need an function that decreases the length of this array by 1 every time it's called. I've tried doing it with .reduce() and just trying to set the old array as array - 1 but nothing works as expected.



Solution 1:[1]

There are multiple options available.

  • pop() will remove the last element from the array and return it
  • decreasing the length by one will just remove the last element
  • use splice() method

const array = [1, 2, 3, 4, 5];
console.log(array);
// use pop which retrieves the last element from the array and removes it from the array
const lastElement = array.pop();
console.log(`Last element ${lastElement} was removed from the array`);
console.log(array);
// you can also simply decrease the length by one
array.length--;
console.log(array);
// you could also use splice()
array.splice(-1);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Abovementioned methods work on the original array. If you want to instead get a new array (i.e. a copy) with the last element removed use slice():

const array = [1, 2, 3, 4, 5];
const newArray = array.slice(0, -1);
console.log(array);
console.log(newArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1