First n elements

Angelos Chalaris · JavaScript, Array · Jul 22, 2022

Gets the first n elements of an array.

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

Recommended snippets

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

  • Weighted sample

    JavaScript, Array

    Gets a random element from an array, using the provided weights as the probabilities for each element.

  • Find first n matches

    JavaScript, Array

    Finds the first n elements for which the provided function returns a truthy value.