How do you remove the last N elements from an array?

This post will discuss how to remove the last element from an array in JavaScript.

1. Using Array.prototype.pop() function

The standard way to remove the last element from an array is with the pop() method. This method works by modifying the original array. The following code creates an array containing five elements, then removes its last element.

1

2

3

4

5

6

7

8

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

 

var last = arr.pop();

console.log(arr);

 

/*

    Output: [ 1, 2, 3, 4 ]

*/

Download  Run Code

2. Using Array.prototype.splice() function

The splice() method is often used to in-place remove existing elements from the array or add new elements to it. The following example demonstrates the usage of the splice() to remove the last element from the array of length 5.

1

2

3

4

5

6

7

8

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

 

arr.splice(arr.length - 1);

console.log(arr);

 

/*

    Output: [ 1, 2, 3, 4 ]

*/

Download  Run Code

 
You can easily extend the above code to remove the last n elements from the array:

1

2

3

4

5

6

7

8

9

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

var n = 3;

 

arr.splice(arr.length - n);

console.log(arr);

 

/*

    Output: [ 1, 2 ]

*/

Download  Run Code

3. Using Lodash Library

If you’re using the Lodash JavaScript library in your project, you can use the method, which returns everything but the last element of the array. Note that this doesn’t modify the original array but returns a new array.

1

2

3

4

5

6

7

8

9

var _ = require('lodash');

 

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

arr = _.initial(arr);

console.log(arr);

 

/*

    Output: [ 1, 2, 3, 4 ]

*/

Download Code

4. Using Underscore Library

Alternatively, to remove the last n elements from the array, pass n as the second parameter to method of Underscore library.

1

2

3

4

5

6

7

8

9

10

11

var _ = require('underscore');

 

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

var n = 3;

 

arr = _.initial(arr, n);

console.log(arr);

 

/*

    Output: [ 1, 2 ]

*/

Download Code

That’s all about removing the last element from an array in JavaScript.

How do I remove the last 3 elements from a list?

Using del Another efficient, yet simple approach to delete the last element of the list is by using the del statement. The del operator deletes the element at the specified index location from the list. To delete the last element, we can use the negative index -1.

How to remove last n elements from array in PHP?

To remove the last element or value from an array, array_pop() function is used. This function returns the last removed element of the array and returns NULL if the array is empty, or is not an array.

How to remove last two values from array in JavaScript?

Use the splice() method to remove the last 2 elements from an array, e.g. arr. splice(arr. length - 2, 2) . The splice method will delete the 2 last elements from the array and return a new array containing the deleted elements.