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

If the live demo fails to load properly on the website then please use the button to open it in a separate tab

Open Live Demo

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like

React convert JSON to CSV

React convert JSON to CSV using JSONToCSVConvertor function. Suppose you have a table (GUI react table tool) and you want to export it into excel, then this function will come…
View Post

.map is not a function

map() can only be used with Arrays. So, if you are getting error .map is not a function, you are probably using it on either the objects or other variables…
View Post