Limit contents of an Array

Asked

Viewed 1,083 times

3

How can I limit the number of values/indices of a array? For example:

let arr = [1, 2, 3, 4];
console.log(arr)
// Exibirá: [1, 2, 3, 4]

Goal:

//Reduzindo o limite de índices do array para 2:
console.log(arr)
// Exibirá: [1, 2]

Is there any simple way to accomplish this? No use repeating structures or something like?

1 answer

4


An alternative is to use slice:

const arr = [1, 2, 3, 4];
console.log(arr.slice(0, 2)); // [1, 2]

The method slice receives two parameters: the initial and the final index, the initial is included and the final is not. As in arrays the indexes start at zero, if I only want the first two, I use slice(0, 2), Thus the zero and 1 indices are included.

Also remembering that the parameters are optional. If the final index is omitted, it takes until the end of the array. And if the initial is omitted, it takes everything from the beginning of the array:

const arr = [1, 2, 3, 4];

// começa do índice 2 (ou seja, do número 3), até o final do array
console.log(arr.slice(2)); // [3, 4]

// começa do índice 0 até o final do array (ou seja, o array todo)
console.log(arr.slice()); // [1, 2, 3, 4]


Always remembering that slice returns a new array. Therefore, call slice() without arguments is one of the ways to create a copy of the array.


If you always want to get the N first elements of the array, another alternative is to change their size by setting the property length:

const arr = [1, 2, 3, 4];
arr.length = 2; // muda o tamanho do array para 2
console.log(arr); // [1, 2]

Remembering that this option will always catch only the first N elements. If you want to be more flexible (for example, take the third to the tenth element), use slice.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.