First n elements
JavaScript, Array · Jul 22, 2022

Gets the first n
elements of an array.
- Use
Array.prototype.slice()
with a start value of0
and an end value ofn
to get the firstn
elements ofarr
.
const firstN = (arr, n) => arr.slice(0, n);
firstN(['a', 'b', 'c', 'd'], 2); // ['a', 'b']