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.
Asked
Active
Viewed 586 times
0
-
1did you try the pop method? – sorold May 22 '22 at 13:17
-
Or setting the `.length` property to `.length - 1`? – Pointy May 22 '22 at 13:17
1 Answers
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; }

Mushroomator
- 6,516
- 1
- 10
- 27
-
also `splice(-1)` (but it's a [duplicate](https://stackoverflow.com/questions/19544452/remove-last-item-from-array) anyway) – pilchard May 22 '22 at 13:24