0

I have an array myArray=[1, 2, 3, 4, 5]. I need to get items from index 2:3.

In Python this would be:

my_array = [1, 2, 3, 4, 5]
print(my_array[2:3])

How can I accomplish this in javascript?

ubuntuuber
  • 740
  • 1
  • 7
  • 18

3 Answers3

1

You can use the .slice function:

let my_array = [1, 2, 3, 4, 5];
let arr = my_array.slice(2,3);
console.log(arr);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
1

Use Array.prototype.slice()(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice)

let my_array = [1, 2, 3, 4, 5]
console.log(my_array.slice(2,3)) // prints '3'
0

Use Array.slice(first_index, last_index). Note that the element at last_index is not returned, so add 1.

If you want to return [3, 4], use my_array.slice(2,4). Remember, of course, that array indices are zero-based ;)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

Cal McLean
  • 1,408
  • 8
  • 15