get first 20 elements of an array in javascript

To get the first 20 elements of an array in JavaScript, you can use the slice method.

Here's an example:

index.tsx
const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25];

const first20 = myArray.slice(0, 20);

console.log(first20); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
246 chars
6 lines

In this example, we have an array of 25 elements called myArray. We then use the slice method to create a new array containing the first 20 elements of myArray.

The slice method takes two arguments: the starting index and the ending index (non-inclusive). In this case, we pass in 0 as the starting index (the first element of the array) and 20 as the ending index (the 21st element of the array, which is not included).

We then log the new array to the console, which outputs [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20].

gistlibby LogSnag