525

I have the following array.

var arr = [1,0,2];

I would like to remove the last element i.e. 2.

I used arr.slice(-1); but it doesn't remove the value.

Martin Braun
  • 5,873
  • 7
  • 43
  • 81
Prithviraj Mitra
  • 7,940
  • 9
  • 44
  • 80
  • 2
    possible duplicate of [to remove first and last element in array using jquery](http://stackoverflow.com/questions/4644139/to-remove-first-and-last-element-in-array-using-jquery) – JoDev Oct 23 '13 at 14:27
  • 41
    use arr[.pop()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) – Tushar Gupta - curioustushar Oct 23 '13 at 14:27
  • 3
    arr.splice(-1,1) will return to you array [1,0]; arr.slice(-1,1) will return to you [2] – Anja Ishmukhametova May 14 '15 at 03:48
  • 16
    `arr.slice(0,-1)` was the best solution for me – Black Mamba Feb 17 '18 at 09:34
  • 6
    The question is a bit ambiguous since "remove last element" might mean remove the element from the array and keep the array (with one element less). But it might also mean to remove the element and keep the element. First case: `splice()`, second case: `pop()`. – thoni56 Jul 22 '18 at 11:22
  • If you have three apples and one is removed - how many do you have? –  Jun 17 '19 at 04:53

26 Answers26

720

Array.prototype.pop() by JavaScript convention.

let fruit = ['apple', 'orange', 'banana', 'tomato'];
let popped = fruit.pop();

console.log(popped); // "tomato"
console.log(fruit); // ["apple", "orange", "banana"]
Stuart Kershaw
  • 13,825
  • 5
  • 35
  • 47
  • 8
    Array.prototype.pop() appears to be the fastest http://jsperf.com/slice-vs-splice-vs-pop/3 – Daniel Mar 01 '16 at 19:48
  • 1
    When using pop(), be sure not to do jQuery('#foo').val(numbers.pop()), unless you only want to place the last item of the array into the field. pop() returns the element removed. As Stuart has done, first do numbers.pop(); and then do jQuery('#foo').val(numbers)... – Charles Robertson May 12 '17 at 15:17
  • 5
    Best solution +1 – mdlars May 02 '18 at 10:23
  • 5
    it would be cool to have unpop() that returns rest of the array. – eomeroff Dec 11 '18 at 17:19
  • 4
    Any way to do this while keeping the array immutable? – nayiaw Aug 23 '19 at 05:23
  • 5
    @nayiaw Yep, ES6 spread syntax: `let fruit = ['apple', 'orange', 'banana', 'tomato'];` `let popped = [...fruit].pop();` popped then equals `tomato` and fruit still equals `['apple', 'orange', 'banana', 'tomato']`. – Stuart Kershaw Aug 26 '19 at 22:52
  • Does not fit case when you want to string[][].map() and remove last element from each string[] subarray. But it could be solved with rows.forEarch(row => row.pop()) – Viacheslav Dobromyslov Nov 13 '20 at 05:46
604

Use splice(startPosition, deleteCount)

array.splice(-1,1)
CroMagnon
  • 1,210
  • 7
  • 20
  • 32
Anton
  • 30,499
  • 5
  • 42
  • 54
  • Anton what if I want to get the last value only for eg 2 and remove 1,0. – Prithviraj Mitra Oct 23 '13 at 14:39
  • 1
    @PrithvirajMitra You want to remove 1 and 0? So the array ==[2] ? – Anton Oct 23 '13 at 14:40
  • 1
    Then you can do this arr.splice(0,2) @PrithvirajMitra – Anton Oct 23 '13 at 14:47
  • So 0 is the starting position and 2 is first two values? In that case can I do like this arr.splice(0,(arr.length - 1)) ? – Prithviraj Mitra Oct 23 '13 at 15:17
  • @PrithvirajMitra Yeah that should work completly fine, and yea 0 is starting position and 2 is how many you want to remove – Anton Oct 23 '13 at 15:25
  • 3
    Doesn't work for one-element arrays: `[1].splice(-1, 1)` => `[1]` – Tvaroh Nov 01 '14 at 08:38
  • 175
    this is NOT best solution, Best is pop function. Not this. – Tommix Jan 11 '16 at 07:50
  • 6
    Pop on its own will only return the value of the last element. If I understand correctly, @PrithvirajMitra wants two things: 1) To remove the last element from the original array, and 2) return that element as a single element array - ie: `[0,1,2] -> [2]`, leaving behind `[0,1]`. If that's the case, then `[arr.pop()]` will do the trick. – Ben Hull Apr 24 '17 at 03:14
  • 29
    Note that `array.pop()` will change modify `array`, while `slice(0, -1)` will not. Pop is of course faster but may not be always suitable for all needs. – adelriosantiago Sep 23 '17 at 00:40
  • Using splice is a recipe for misunderstanding, Use pop like suggested below – DanLatimer Oct 20 '17 at 19:01
  • be careful using `new var = arr.splice(-1,1)` this returns the spliced value and not the new array. (just happened to me) First splice and then set the `new var` – vinni Nov 13 '17 at 15:10
  • wtf?? it returns empty array – Toolkit Dec 25 '17 at 14:58
  • In short, use `pop()`. – int soumen Dec 26 '17 at 10:44
  • this solution is just great if you want to "drop all but the last item". But it should not be the correct answer in this thread – nils petersohn Mar 06 '19 at 10:27
  • wrong: pop() returns the removed element, splice() returns the spliced selection - better use arr.filter((e, i) => i !== arr.length - 1) or do as @vinni said – Cristialt Oct 23 '19 at 09:47
  • If you want to remove n element from array: arr.splice(-n, n); – efirat Oct 24 '19 at 11:51
  • @BenHull `[1].splice(-1, 1)` > returns removed item, thats why you see `[1]` at the end. However, if you try this`var a = [1]; a.splice(-1, 1); ` you will see `a : []` – efirat Oct 24 '19 at 11:55
  • It's important to know about side effects. If you *want* to modify the original, then use `pop()`, if you don't, use `splice()`. `splice()` is like creating a defensive copy, once the copy is made you can do whatever you want to it and not worry about the original. In my case, I `return array.filter(...).splice(...)` `pop()` is useful when you have a to-do list for example, and you want to mutate it every time. If I used pop for my case, it would have caused bugs. If the array only has a few items in it performance is negligible. Mine had 13 items. Memory and cpu are not at stake. – grego Jan 08 '20 at 01:22
  • Thanks! Good Job – unknown May 27 '21 at 05:11
310

You can do this using .slice() method like:

arr.slice(0, -1);    // returns [1,0]

Here is a demo:

var arr = [1, 0, 2];
var newArr = arr.slice(0, -1);    // returns [1,0]

console.log(newArr);
$('#div1').text('[' + arr + ']');
$('#div2').text('[' + newArr + ']');
<script src="http://code.jquery.com/jquery.min.js"></script>
<b>Original Array    : </b>
<div id="div1"></div>
<br/>
<b>After slice(0, -1): </b>
<div id="div2"></div>

instead of doing :

arr.slice(-1);   // returns [2]

Here is a demo:

var arr = [1, 0, 2];
var newArr = arr.slice(-1);    // returns [2]

console.log(newArr);
$('#div1').text('[' + arr + ']');
$('#div2').text('[' + newArr + ']');
<script src="http://code.jquery.com/jquery.min.js"></script>
<b>Original Array    : </b>
<div id="div1"></div>
<br/>
<b>After slice(-1): </b>
<div id="div2"></div>

Explanation:-

Now the basic syntax of Array.prototype.slice() or in short slice() method is:

arr.slice([begin[, end]])

Here,

the begin parameter is zero-based index at which extraction from an array starts. So, lets say based on above example if we do something like

arr.slice(0)    // returns [1,0,2]

it would return all the array elements from start of sequence from position 0 and that is [1,0,2]. Similarly, if we do

arr.slice(1)    // returns [0,2]

it would return [0,2] since 0 is at position 1 here and everything after that. Now, in your case you have passed a negative index i.e., -1 as the begin parameter, which indicates an offset from the end of the sequence. So, slice(-1) in your case extracts the last one array element in the sequence and that is 2 (as we have already seen in the above demo).

Now, let's talk about the end parameter in the slice() method syntax here. It is again a zero-based index at which extraction from an array ends. So, lets say we have a array like:-

var arr = [1, 0, 2, 5, 3, 9];

and we want to get just the 2,5,3 elements in the array. Now, position of 2 from start of the sequence is 2 and for last element 3 it is 4. We will need to end the extraction here a position 5, as we need to get the element before that position. So, we will simply implement slice() method here like

arr.slice(2, 5)    // returns [2,5,3]

In your case, we have implemented -1 as the end parameter, so our code is like

arr.slice(0, -1)   // returns [1,0]

As a negative index, end indicates an offset from the end of the sequence. So, slice(0,-1) extracts the first element through the second-to-last element in the sequence. So, we get the desired output. We can also do like

arr.slice(0, 2)    // returns [1,0]

we will get the same output. But, I have used -1 here as its easier to implement even for a long array like

[0,2,3,1,2,9,3,6,3,9,1,0,2,9,0,1,1,2,3,4,7,9,1]

If you just want to remove the last element, you don't want to sit & calculate the position of last 9 here and the do like arr.slice(0, 22). You can then simply implement the negative index logic here & do

arr.slice(0, -1) // same result as arr.slice(0, 22)

Hope it helps!

palaѕн
  • 64,836
  • 15
  • 100
  • 121
  • 16
    This works great, just make sure you notice that this is a call to .slice() and not to .s**p**lice(). – Brian Hasden Oct 17 '14 at 20:44
  • 4
    It should be noted that this solution **does not remove** the last item from the array `arr` but rather returns a new array which excludes that last item. As Mozilla's docs say: "The slice() method returns a shallow copy of a portion of an array into a new array object.". – F Lekschas Oct 08 '15 at 00:18
  • 4
    The sample code of the question implicitly ask how to get a new array with the last value removed from the original array. So `arr.slice(0, -1)` is the best answer. – Tsounabe Oct 20 '16 at 11:59
  • 4
    slice is better since it doesn't modify original array – user365314 Jan 29 '19 at 20:43
103

learn by example:

let array_1 = [1,2,3,4];
let array_2 = [1,2,3,4];
let array_3 = [1,2,3,4];
let array_4 = [1,2,3,4];

array_1.splice(-1,1)  // returned --> [4]      array_1 = [1,2,3]
array_2.slice(0,-1);  // returned --> [1,2,3]  array_2 = [1,2,3,4]
array_3.pop();        // returned --> 4        array_3 = [1,2,3]
array_4.shift();      // returned --> 1        array_4 = [2,3,4]
Lukas Liesis
  • 17,690
  • 7
  • 93
  • 89
45

You would need to do this since slice doesn't alter the original array.

arr = arr.slice(-1);

If you want to alter the original array you can use splice:

arr.splice(-1, 1);

or pop:

arr.pop();
Bill Criswell
  • 28,428
  • 3
  • 69
  • 65
29

I would consider .pop() to be the most 'correct' solution, however, sometimes it might not work since you need to use array without the last element right there...

In such a case you might want to use the following, it will return [1,2,3]

var arr = [1,2,3,4];
console.log(arr.splice(0,arr.length-1));

while .pop() would return 4:

var arr = [1,2,3,4];
console.log(arr.pop());

which might not be desirable...

Hope this saves you some time.

Matas Vaitkevicius
  • 49,230
  • 25
  • 212
  • 228
18

There is a function for that, explanation here:

arr.pop();
JoDev
  • 6,018
  • 1
  • 20
  • 33
17

Just use the following for your use case:

var arr = [1,2,3,4];
arr.pop() //returns 4 as the value
arr // value 4 is removed from the **arr** array variable

Just a note. When you execute pop() function even though the line returns the popped item the original array is effected and the popped element is removed.

LordDraagon
  • 436
  • 6
  • 24
Wannes
  • 368
  • 3
  • 13
12

You could simply use, arr.pop()

This removes the last entry of the array.

var arr = [1,0,2]; 
var popped = arr.pop();//Now arr = [1,0] & popped = 2
Venkata Krishna
  • 13,950
  • 5
  • 37
  • 55
9

You can do it in two way using splice():

  1. arr.splice(-1,1)
  2. arr.splice(arr.length-1,1)

splice(position_to_start_deleting, how_many_data_to_delete) takes two parameter.

position_to_start_deleting : The zero based index from where to start deleting. how_many_data_to_delete : From indicated index, how many consecutive data should be deleted.

You can also remove the last element using pop() as pop() removes the last element from some array.
Use arr.pop()

Harunur Rashid
  • 3,825
  • 1
  • 16
  • 18
8

arr.slice(-1) will return a copy of the last element of the array, but leaves the original array unmodified.

To remove the last n elements from an array, use arr.splice(-n) (note the "p" in "splice"). The return value will be a new array containing the removed elements.

Simpler yet, for n == 1, use val = arr.pop()

Alnitak
  • 313,276
  • 69
  • 379
  • 466
6

Another approach is to filter based on index:

arr.filter((element, index) => index < arr.length - 1);

Note: filter() creates new array, doesn't change existing one.

Elnoor
  • 2,614
  • 3
  • 22
  • 32
5

splice(index,howmany) - This solution sounds good. But This howmany will work only for the positive array index. To remove last two items or three items use the index itself.

For example, splice(-2) to remove last two items. splice(-3) for removing last three items.

Parthyz
  • 161
  • 2
  • 4
5
var arr = [1,0,2];
arr.length--; 

// removes the last element // need to check if arr.length > 0

Nirav Shah
  • 69
  • 1
  • 2
5

This method is more helpful to delete and store the last element of an array.

var sampleArray = [1,2,3,4];// Declaring the array
var lastElement = sampleArray.pop();//this command will remove the last element of `sampleArray` and stores in a variable called `lastElement` so that you can use it if required.

Now the results are:

console.log(sampleArray); //This will give you [1,2,3]
console.log(lastElement); //this will give you 4
razat naik
  • 51
  • 1
  • 3
5
var a = [1,2,3,4,5,6]; 
console.log(a.reverse().slice(1).reverse());
//Array(5) [ 1, 2, 3, 4, 5 ]
Daphoque
  • 3,588
  • 1
  • 13
  • 22
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Vasilisa Feb 18 '19 at 11:19
4

It's worth noting that slice will both return a new array, whereas .pop() and .splice() will mutate the existing array.

If you like handling collections of data with a chained command style, you will really want to stick with slice for something like this.

For example:

myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var newArrayOfThings = myArray
  .filter(x => x > 5)              // only bigly things
  .slice(-1)                       // get rid of the last item
  .map(x => `The number is: ${x}`);// map to a set of strings

It can require a lot more messing about, and variable management, to do the same kind of thing with "pop", since unlike map, filter, etc, you don't get a new array back.

It's the same kind of thing with push, which adds an item to the end of an array. You might be better off with concat since that lets you keep the flow going.

myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var newArrayOfThings = myArray
  .filter(x => x > 5)              // only bigly things
  .slice(-1)                       // get rid of the "10"
  .concat([100])                   // note with concat, you must pass an array
  .map(x => `The number is: ${x}`) // map to a set of strings
  
pete otaqui
  • 1,232
  • 11
  • 9
4

With Lodash you can use dropRight, if you don't care to know which elements were removed:

_.dropRight([1, 2, 3])
// => [1, 2]

_.dropRight([1, 2, 3], 2);
// => [1]
Tomas Buteler
  • 3,484
  • 3
  • 25
  • 40
3

2019 ECMA5 Solution:

const new_arr = arr.reduce((d, i, idx, l) => idx < l.length - 1 ? [...d, i] : d, [])

Non destructive, generic, one-liner and only requires a copy & paste at the end of your array.

  • 1
    'Non destructive' doesn't sound like what the original question wants: `I would like to remove the last element `. That needs a destructive/mutating operation on the original array. – Ben Hull Oct 24 '19 at 12:49
2

say you have var arr = [1,0,2]

arr.splice(-1,1) will return to you array [1,0]; while arr.slice(-1,1) will return to you array [2];

Félix Gagnon-Grenier
  • 7,344
  • 10
  • 45
  • 58
Anja Ishmukhametova
  • 1,308
  • 14
  • 14
1

This is good way to remove last item :

if (arr != null && arr != undefined && arr.length > 0) {
      arr.splice(arr.length - 1, 1);
}

Detail of splice as following:

splice(startIndex, number of splice)

Jainish Jariwala
  • 298
  • 2
  • 14
1
var stack = [1,2,3,4,5,6];

stack.reverse().shift();

stack.push(0);

Output will be: Array[0,1,2,3,4,5]. This will allow you to keep the same amount of array elements as you push a new value in.

Blackspade
  • 35
  • 4
1

If you want to remove n item from end of array in javascript, you can easily use:

arr.splice(-n, n);
efirat
  • 3,083
  • 2
  • 35
  • 38
1

Using the spread operator:

const a = [1,2,3]
const [, ...rest] = a.reverse();
const withoutLast = rest.reverse();
console.log(withoutLast)
Tudor Morar
  • 2,720
  • 21
  • 20
0

Simply arr.splice(-1) will do.

Sumit Ramteke
  • 1,417
  • 1
  • 17
  • 36
-1
// Setup
var myArray = [["John", 23], ["cat", 2]];

// Only change code below this line
var removedFromMyArray;
removedFromMyArray = myArray.pop()
Ali HaMza
  • 62
  • 3