skip to Main Content

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


  1. 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)))
    Login or Signup to reply.
  2. 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)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search