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

4
  • 1
    arr.splice(1, -1) Commented Mar 6, 2020 at 15:38
  • @JonasWilms fails for all but []. Commented Mar 6, 2020 at 15:39
  • arr.reduce((acc,curr,i)=>i===0||i===arr.length-1?[...acc,curr]:acc,[]) Commented Mar 6, 2020 at 15:52
  • @WillJenkins there's an open spot in the next Obfuscated Coding competition for you ;-) Commented Mar 6, 2020 at 19:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.