# 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?

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);
``````

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``````

Something like this?

``````var allPoints = [0, 1, 2, 3, 4, 5],
midPoints = []

/*start the iteration at index 1 instead of 0 since we want to skip the first point anyway and stop iteration before the final item in the array*/
for (var i = 1; i < (allPoints.length - 1); i++) {
midPoints.push(allPoints[i]);
}

console.log(midPoints);``````

Everything is much easier, use the filter method

``````let Arr = ['first', 'A', 'B', 'C', 'last'];
NewArr = Arr.filter((item,i) => i !== 0 && i !== Arr.length-1);
console.log(NewArr)
``````

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Making sure at least one checkbox is checked