Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all array elements except for first and last

Tags:

I have an array of locations, I need to be able to access origin, middlepoints and destination separately.

I know that my origin is always the first element and the destination is always the last element but I can't figure out how can I dynamically can access all the middlepoints?

like image 857
Vilius Avatar asked Aug 21 '17 15:08

Vilius


People also ask

How do you get all elements in an array except the first?

You can use array. slice(0,1) // First index is removed and array is returned. FIrst index is not removed, a copy is created without the first element.

How do you find an array without the first element?

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

How do you remove the first and last element of an array?

To remove the first and last elements from an array, call the shift() and pop() methods on the Array. The shift method removes the first and the pop method removes the last element from an array.


Video Answer


1 Answers

Since there is no data I am taking a basic array to show. Also by this method you will preserve your original array.

var arr = [1,2,3,4,5,6,7];
var middle = arr.slice(1, -1);
console.log(middle);

OR

var arr = [1,2,3,4,5,6,7];
var middle = arr.slice(1, arr.length-1);
console.log(middle);
like image 110
Naren Murali Avatar answered Sep 21 '22 09:09

Naren Murali