Prithviraj Mitra
Prithviraj Mitra

Reputation: 11842

Remove last item from array

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.

Upvotes: 856

Views: 1495862

Answers (29)

palaѕн
palaѕн

Reputation: 73966

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

var arr = [1,0,2]
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 an 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)

Upvotes: 476

Stuart Kershaw
Stuart Kershaw

Reputation: 17701

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"]

Upvotes: 1044

Nirav Shah
Nirav Shah

Reputation: 77

var arr = [1,0,2];
arr.length--; 

removes the last element, but you might need to check if arr.length > 0 first.

Upvotes: 5

Everything Digital
Everything Digital

Reputation: 191

If you're looking for a one-liner that doesn't require you to initialize multiple variables:

var arr = [1,0,2];

arr = arr.filter((_,i,a) => i !== (a.length-1));

Explanation: We're using the Array Filter Method which takes in 3 callbacks:

  1. element (_): the current element during the iteration
  2. index (i): the index of the element iteration
  3. array (a): the array that is being used for the filter

So we just skip the element if it's the last element in the array that is being used.

The _ is just a placeholder because we're not actually using it.

Upvotes: 2

Sahil Thummar
Sahil Thummar

Reputation: 2500

var arr = [ 0, 1, 2, 3, 4, 5, 6, 7 ];

// using slice
arr = arr.slice(0, -1);
console.log('arr : ', arr);

// using splice
arr.splice(-1);
console.log('arr : ', arr);

// using pop
arr.pop();
console.log('arr : ', arr);

// using shift and reverse
arr.reverse().shift()
arr.reverse();
console.log('arr : ', arr);

// using spread Operator and reverse
const [, ...exceptLast] = arr.reverse();
arr = exceptLast.reverse();
console.log('arr : ', arr);

// removing last index
arr.length -= 1;
console.log('arr : ', arr);

Upvotes: 11

Bill Criswell
Bill Criswell

Reputation: 32941

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

arr = arr.slice(0, -1);

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

arr.splice(-1, 1);

or pop:

arr.pop();

Upvotes: 109

Arjix
Arjix

Reputation: 158

I got the best answer!

var array = [1, 2, 3, 4]
array.length = array.length - 1

console.log(array)
> [1, 2, 3]

Honestly JS is a meme at this point.

PS: This affects the variable and any of its references, if you want to not affect any of the variable's references you can do:

var array = [1, 2, 3, 4]
var modifiedArray = Array.from(array)
modifiedArray .length = modifiedArray .length - 1

console.log(modifiedArray )
> [1, 2, 3]

Upvotes: -9

Anton
Anton

Reputation: 32591

Use splice(startPosition, deleteCount)

array.splice(-1)

var array = ['abc','def','ghi','123'];
var removed = array.splice(-1);  //last item
console.log( 'array:', array );
console.log( 'removed:', removed );

Upvotes: 759

pete otaqui
pete otaqui

Reputation: 1472

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(0, -1)                       // get rid of the last item ! slice(-1) will give first element
  .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
  

Upvotes: 12

Lukas Liesis
Lukas Liesis

Reputation: 26413

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]

Upvotes: 186

Ali Hamza Yaseen
Ali Hamza Yaseen

Reputation: 140

// Setup
var myArray = [["John", 23], ["cat", 2]];

// Only change code below this line
var removedFromMyArray;
removedFromMyArray = myArray.pop()

Upvotes: -1

Sumit Ramteke
Sumit Ramteke

Reputation: 1496

Simply arr.splice(-1) will do.

Upvotes: 0

Tudor Morar
Tudor Morar

Reputation: 3868

Using the spread operator:

const a = [1,2,3]
const [, ...rest] = a.reverse();
const withoutLast = rest.reverse();
console.log(withoutLast)

Upvotes: 2

Wannes
Wannes

Reputation: 359

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.

Upvotes: 20

Elnoor
Elnoor

Reputation: 3762

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.

Upvotes: 8

efirat
efirat

Reputation: 3867

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

arr.splice(-n, n);

Upvotes: 1

Santiago M. Quintero
Santiago M. Quintero

Reputation: 1273

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.

Upvotes: 3

Matas Vaitkevicius
Matas Vaitkevicius

Reputation: 61509

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.

Upvotes: 31

Daphoque
Daphoque

Reputation: 4678

var a = [1,2,3,4,5,6]; 
console.log(a.reverse().slice(1).reverse());
//Array(5) [ 1, 2, 3, 4, 5 ]

Upvotes: 5

Harun Or Rashid
Harun Or Rashid

Reputation: 5947

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()

Upvotes: 9

Tomas Buteler
Tomas Buteler

Reputation: 4137

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]

Upvotes: 4

Blackspade
Blackspade

Reputation: 45

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.

Upvotes: 1

razat naik
razat naik

Reputation: 61

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

Upvotes: 6

Jainish Jariwala
Jainish Jariwala

Reputation: 308

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)

Upvotes: 1

Anja Ishmukhametova
Anja Ishmukhametova

Reputation: 1564

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];

Upvotes: 2

Parthyz
Parthyz

Reputation: 161

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.

Upvotes: 5

JoDev
JoDev

Reputation: 6873

There is a function for that, explanation here:

arr.pop();

Upvotes: 19

Alnitak
Alnitak

Reputation: 339985

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()

Upvotes: 12

Venkata Krishna
Venkata Krishna

Reputation: 15112

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

Upvotes: 14

Related Questions