If I want to get the second element of an array, I simply index it with 1:
const arr = [2, 3, 5, 7, 11]
console.log(arr[1])
Outputs 3
Is there a way to index multiple elements of an array with an array of indices? Something like this (which doesn’t work):
const arr = [2, 3, 5, 7, 11]
const indices = [1, 2, 4]
console.log(arr[indices])
Should output [3, 5, 11]
But actually outputs undefined
2
Answers
Sure. You’ve made a 2nd array of indices you want, so just loop through them.
Even simpler is to use
map
to transform the values, or to usefilter
to narrow down the original array. Both produce the same result here, it just depends on what you may need for whatever you are putting this into.One can use the
filter()
method on the array as wellI used
_
as the first parameter since it is not utilized