Take more than one element from an Array

Asked

Viewed 57 times

7

I wonder how I get 2 elements of an array at once.

numeros = [1, 2, 3]
let primeiros = numeros[1]

but I need to take the first 2 values, and I haven’t found how to do.
I need something like:

let primeiros = numeros[1:2]
  • 1

    I understand it’s not what you need right now, but knowing it might help at some point: const [primeiro, segundo] = [1,2,3]

1 answer

7


Use Array.prototype.slice():

let numeros = [1, 2, 3];
let primeiros = numeros.slice(0, 2);
console.log(primeiros);

The parameters represent, respectively, the first index you want, and the indices following the last one desired.

  • A possibility also described in another answer: https://stackoverflow.com/questions/39547784/select-multiple-array-elements-javascript

Browser other questions tagged

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