Search code examples
javascriptone-liner

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


Solution

  • 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