In this code snippet we’ll show examples to get items from the first or last (start or end) items from a JavaScript array.
Get the first item from an array
const take = (arr, n = 1) => arr.slice(0, n); take([1, 2, 3], 0); // [] take([1, 2, 3], 2); // [1, 2] take([1, 2, 3], 5); // [1, 2, 3]
Get the last item from an array
const takeRight = (arr, n = 1) => n === 0 ? [] : arr.slice(-n); takeRight([1, 2, 3], 2); // [2, 3] takeRight([1, 2, 3], 0); // [] takeRight([1, 2, 3], 5); // [1, 2, 3]
Note: Negative values can cause erroneous results.
CC BY 4.0 added intro and tags – 30 Seconds of Code
Tags: n items from array, start items from array, last items from array, javascript, js, array, array slice, slice, take