Hao Wu
Hao Wu

Reputation: 20699

What's the idiomatic way to get the last element from a generated array?

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

Upvotes: 2

Views: 331

Answers (2)

Mat
Mat

Reputation: 100

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

[...getArray()].reverse()[0]

Upvotes: 0

dave
dave

Reputation: 64657

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

Upvotes: 3

Related Questions