Es6 Array Limit First n Elements using Array.slice()

Es6 Array Limit First n Elements


We get the first n elements easily using the Array.slice() method. The slice() method returns selected elements in an array, as a new array but does not modify the array. The slice() method selects from a given start and up to a (not inclusive) given end as shown below;

array.slice(start, end)

The 'start' parameter is the start position while the 'end' parameter is the end position.

The default start position is 0, while the default end position is the last element.

Negative numbers are always selected from the end of the array.  

The Return value contains the selected elements.

The method is particularly useful where the list of array items is long and only a section of the list is needed for display. The selected elements can further be used for assignments and the declaration of a variable.

Code Example

const list = ["apple", "banana", "orange", "strawberry"];  
const n = 3;  
const items = list.slice(0, n);  

The output will be –

["apple", "banana", "orange"]

In the code above;

Our ArrayList consists of four types of fruits.

To get the first n elements from an Array, we call the slice method on the array, passing in 0 as the first parameter and the number of elements to get as 3, e.g. list.slice(0, 3) returns a new array with the first 3 elements of the original array.

The return value becomes "apple", "banana", "orange"

You can further see how array.slice() works in the live demo below;

Live Demo

Open Live Demo