-3

What is the best way to get only the first and last value in Array?

If arr = [0,1,2,3]

Result: arr = [0,3]

If arr = [0]

Result: arr = [0]

If arr = []

Expect result: arr = []

I could get in this way.

[arr[0], arr[arr.length - 1]]

But I want to know if there is a better way to get.

Remy Wang
  • 666
  • 6
  • 26

1 Answers1

2
function firstLast(arr) {
    if (arr.length < 2) return arr;
    return [arr[0], arr[arr.length - 1]];
}

Error check for the case where the length of the array is less than 2, if so, just return the array.

If the array is long enough to get start and end, just return a new array with that start and end.

GTBebbo
  • 1,198
  • 1
  • 8
  • 17