-1

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

0

2 Answers 2

2

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 use filter 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.

const arr = [2, 3, 5, 7, 11];
const indices = [1, 2, 4];

console.log('map', indices.map(i => arr[i]))

console.log('filter', arr.filter((val, i) => indices.includes(i)))

Sign up to request clarification or add additional context in comments.

Comments

0

One can use the filter() method on the array as well

I used _ as the first parameter since it is not utilized

const arr = [2, 3, 5, 7, 11];
const indices = [1, 2, 4];

const result = arr.filter((_, index) => indices.includes(index));
console.log(result)

3 Comments

Seems pretty inefficient
no is not? and it's pretty much the same approach the guy above gave you as an option whose answers you accepted
The map mechanism is O(n), while the filter mechanism is O(m·n)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.