Skip to content

Get all array elements except for first and last

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?

Answer

To achieve this you can use shift() and pop() to get the first and last elements of the array, respectively. Whatever is left in the array after those operations will be your ‘middlepoints’. Try this:

var middlePoints = ['start', 'A', 'B', 'C', 'end'];
var origin = middlePoints.shift();
var destination = middlePoints.pop();

console.log(origin);
console.log(middlePoints);
console.log(destination);

shift and pop affects the current array; Is there a way to get the middlePoints changing the current array?. Like slice, but slice do not affect it

Sure, you can use filter() for that, checking the index of the item in the array:

var input = ['start', 'A', 'B', 'C', 'end'];
var output = input.filter((v, i) => i !== 0 && i !== input.length -1);

console.log(input); // original value retained
console.log(output); // copied via filter