135

How to remove first and last element in an array?

For example:

var fruits = ["Banana", "Orange", "Apple", "Mango"];

Expected output array:

["Orange", "Apple"]
1
  • 10
    this looks like a 'soft ball' for creating links to w3schools, you've even used the same array elements. ;-)
    – Myster
    Commented Jun 11, 2012 at 2:54

17 Answers 17

161
fruits.shift();  // Removes the first element from an array and returns only that element.
fruits.pop();    // Removes the last element from an array and returns only that element. 

See all methods for an Array.

5
  • It's easier with jQuery UI myArray.effect( "transfer", { item: 'first&&last', to: bin});
    – iConnor
    Commented Aug 31, 2013 at 8:56
  • 4
    Dear downvoters, you might want your downvotes to be helpful, so please add a comment explaining what's wrong with the answer..
    – user180100
    Commented Jun 18, 2014 at 12:12
  • 3
    This will return only that removed (first or last) element's value, not remaining array Commented Jan 13, 2015 at 6:41
  • @RC. Just want to inform User about actual work of function. I am questioning on your answer. Commented Jan 15, 2015 at 6:40
  • 2
    Like User use this function as same as you write it definatly works proper as remove element, BUT if user write return fruits.shift() it will return ONLY that first element and then remove from array. Commented Jan 15, 2015 at 6:44
116

Creates a 1 level deep copy.

fruits.slice(1, -1)

Let go of the original array.

Thanks to @Tim for pointing out the spelling errata.

4
  • 5
    I think you mean slice() rather than splice().
    – Tim Down
    Commented Jan 10, 2011 at 10:02
  • 91
    Slicing fruit is way better than popping or shifting fruit.
    – pettys
    Commented May 9, 2012 at 19:12
  • 3
    with increment popularity of redux, functional javscript and immutable things this answer is way better
    – nkint
    Commented Feb 9, 2016 at 10:31
  • or arr.slice(n, -n) to remove any number from each end Commented Aug 26, 2022 at 21:55
26

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var newFruits = fruits.slice(1, -1);
console.log(newFruits); //  ["Orange", "Apple"];

Here, -1 denotes the last element in an array and 1 denotes the second element.

1
  • Or just fruits = fruits.slice(1,-1); if you don't have to create a new variable. Commented Apr 11, 2018 at 4:52
9

I use splice method.

fruits.splice(0, 1); // Removes first array element

var lastElementIndex = fruits.length-1; // Gets last element index

fruits.splice(lastElementIndex, 1); // Removes last array element

To remove last element also you can do it this way:

fruits.splice(-1, 1);

See Remove last item from array to see more comments about it.

1
  • 1
    Might as well use shift() or pop() if you're mutating the array.
    – anolan23
    Commented Jul 25, 2022 at 23:29
5

push() adds a new element to the end of an array.
pop() removes an element from the end of an array.

unshift() adds a new element to the beginning of an array.
shift() removes an element from the beginning of an array.

To remove first element from an array arr , use arr.shift()
To remove last element from an array arr , use arr.pop()

2

This can be done with lodash _.tail and _.dropRight:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(_.dropRight(_.tail(fruits)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

2

You can use Array.prototype.reduce().

Code:

const fruits = ['Banana', 'Orange', 'Apple', 'Mango'],
      result = fruits.reduce((a, c, i, array) => 0 === i || array.length - 1 === i ? a : [...a, c], []);

console.log(result);

1
  • Cool to see reduce to remove the first and last item!
    – Mohan Ram
    Commented Oct 6, 2017 at 6:09
2

For avoiding Mutation and changing the source array, a ReactJS developer cannot use pop, shift function, because both will change the source array and this kind of changes are root of very deep bugs.

The best way is using slice JavaScript built-in function. This function will create a slice of the source array and return for you a new array, also it accept negative index numbers, it means the first negative number is the latest item in array. so:

fruits.slice(a, b)
  • The first argument means start from index a and the index a - 1 isn't wanted.
  • The second argument means slice end in index b - 1 and the index b isn't wanted.

So by the above explanation if we put a = 1 it means we don't want first element and if we put b = latest it means slicing will end in index b - 1 and we don't what index b.

: What was the index of latest element in the slice function? correct -1.

✅ So the final answer is:

fruits.slice(1, -1)
1

To remove element from array is easy just do the following

let array_splited = [].split('/');
array_splited.pop()
array_splited.join('/')
1

var fruits = ["Banana", "Orange", "Apple", "Mango"];
// don't change original use slice(), syntax: slice(optional start parameter, optional end parameter)
// remove first and last element
var newFruits = fruits.slice(1, -1)
console.log(newFruits)

// edit original use splice(), syntax: splice(start, optional delete count, optional items to add)
// remove first and last element
fruits.splice(0, 1)
fruits.splice(-1, 1)
console.log(fruits)

// good information about slice vs splice
// https://www.freecodecamp.org/news/javascript-slice-and-splice-how-to-use-the-slice-and-splice-js-array-methods/

0

Say you have array named list. The Splice() function can be used for both adding and removing item in that array in specific index i.e that can be in the beginning or in the end or at any index. On the contrary there are another function name shift() and pop() which is capable of removing only the first and last item in the array.

This is the Shift Function which is only capable of removing the first element of the array

var item = [ 1,1,2,3,5,8,13,21,34 ]; // say you have this number series 
item.shift(); // [ 1,2,3,5,8,13,21,34 ];

The Pop Function removes item from an array at its last index

item.pop(); // [ 1,2,3,5,8,13,21 ];

Now comes the splice function by which you can remove item at any index

item.slice(0,1); // [ 2,3,5,8,13,21 ] removes the first object
item.slice(item.length-1,1); // [ 2,3,5,8,13 ] removes the last object 

The slice function accepts two parameters (Index to start with, number of steps to go);

0

I over through all the notable answers. I am pointing you out a different answer. It works for me. I hope it will help you

fruits.slice(1,fruits.length-1)
0

Using slice(1, -1):

Example
> l = [5, 3, 10, 6]
[ 5, 3, 10, 6 ]
> l.slice(1, -1)
[ 3, 10 ]

0

Another option is to use the delete operator, then filter the array:

const myArray = [1, 2, 3, 4];

// Delete the first item
delete myArray[0];
// Delete the last item
delete myArray[myArray.length - 1];

console.log(myArray) // Output: [null, 2, 3, null]

const finalResult = myArray.filter(x => x);

console.log(finalResult) // Output [2, 3]

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

-1

You used Fruits.shift() method to first element remove . Fruits.pop() method used for last element remove one by one if you used button click. Fruits.slice( start position, delete element)You also used slice method for remove element in middle start.

1
-1
var resident_array =  ["RC_FRONT", "RC_BACK", "RC_BACK"];
var remove_item = "RC_FRONT";
resident_array = $.grep(resident_array, function(value) {
            return value != remove_item;
    });
resident_array = ["RC_BACK", "RC_BACK"];
1
  • Remove first element from array.
    – vikas pal
    Commented Oct 6, 2017 at 6:16
-1

To remove the first and last element of an array is by using the built-in method of an array i.e shift() and pop() the fruits.shift() get the first element of the array as "Banana" while fruits.pop() get the last element of the array as "Mango". so the remaining element of the array will be ["Orange", "Apple"]

3

Not the answer you're looking for? Browse other questions tagged or ask your own question.