1

I want to get the last element from a generated array in a single line, is there a better way to do it?

I was thinking assign the array to foo then immediatly assign the last element of foo to itself again but it doesn't work:

function* getArray() {
  yield* [1, 2, 3];
}

let foo = (foo = [...getArray()], foo[foo.length - 1]);

console.log(foo); // 3?

This works but it's calling getArray() twice which is quite unnecessary.

function* getArray() {
  yield* [1, 2, 3];
}

let foo = [...getArray()][[...getArray()].length - 1];

console.log(foo); // 3
Hao Wu
  • 17,573
  • 6
  • 28
  • 60
  • 2
    Use [`.at(-1)`](//github.com/tc39/proposal-relative-indexing-method), `.at(-2)`, etc. which is also mentioned here: [Get the last item in an array](/a/61847169/4642212). Use this [polyfill](//github.com/tc39/proposal-relative-indexing-method#polyfill). I’d recommend checking the existence of the method before adding it. Alternatively, `.slice(-1)[0]`, `.slice(-2)[0]`, etc. are idiomatic. – Sebastian Simon Jun 09 '21 at 07:45
  • storing the whole generator in memory just to pull the last element is suboptimal – georg Jun 09 '21 at 08:22
  • @georg There’s also the [Double-Ended Iterator and Destructuring proposal](//github.com/tc39/proposal-deiter). – Sebastian Simon Jun 09 '21 at 08:28
  • @SebastianSimon: in up-to-date javascript, this would be as simple as `for(x of iter) {}; return x` – georg Jun 09 '21 at 08:38

2 Answers2

3

You could just .pop() it

The pop() method removes the last element from an array and returns that element.

function* getArray() {
  yield* [1, 2, 3];
}

let foo = [...getArray()].pop()
console.log(foo); // 3

let bar = [...getArray()].slice(-2)[0]
console.log(bar); // 2

let baz = [...getArray()].splice(-2, 1)[0]
console.log(baz); // 2
dave
  • 62,300
  • 5
  • 72
  • 93
0

Here's one way to do it in a single statement:

[...getArray()].reverse()[0]
Mat
  • 66
  • 7