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?
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?
You can use the .slice
function:
let my_array = [1, 2, 3, 4, 5];
let arr = my_array.slice(2,3);
console.log(arr);
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'
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