One is the slice() method and second one filter() method. Let’s see at each of them one by one.
The slice() function is used to obtain the top n elements from an array. It’s the most convenient way to obtain things. The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (where end is not included). In this the start and end represents the index of items in the given array. The original array will not be modified.
const arr = [11, 12, 13, 14, 15, 16, 17, 18, 19, 110]; // get the first 5 elements const n = 5; const newArr = arr.slice(0, n); console.log(newArr); // [11, 12, 13, 14, 15]
To filter the first n records from the array, we’ll need to use the filter the elements by index.
const arr = [11, 12, 13, 14, 15, 16, 17, 18, 19, 110]; // get the first 5 elements const n = 5; const newArr = arr.filter((x, i) => i < n); console.log(newArr); // [11, 12, 13, 14, 15]
Hope you have understood the syntax and the code used above. Comment below in case you have any doubts.