Last n elements

JavaScript, Array · Jul 23, 2022

Gets the last n elements of an array.

const lastN = (arr, n) => arr.slice(-n);
lastN(['a', 'b', 'c', 'd'], 2); // ['c', 'd']

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • N random elements in array

    Gets n random elements at unique keys from an array up to the size of the array.

    JavaScript, Array · Oct 22, 2020

  • First n elements

    Gets the first n elements of an array.

    JavaScript, Array · Jul 22, 2022

  • Ungroup array elements based on function

    Creates an array of elements, ungrouping the elements in an array produced by zip and applying the provided function.

    JavaScript, Array · Jan 23, 2022