How to get an array of values based on an array of indexes?

14,581

Solution 1

for(var i = 0; i < indexArr.length; i++)
  resultArr.push(fruitier[indexArr[i]]);

Solution 2

Use .map:

let resultArr = indexArr.map(i => fruitier[i])

Solution 3

If you want to achieve that with lodash, use _.at():

var fruitier = ['apple', 'orange', 'grapes', 'pineapple', 'fig', 'banana', 'jackfruit', 'pomegranate'];
var indexArr = [0, 2, 4];
var resultArr = _.at(fruitier, indexArr);

console.log(resultArr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script>

Solution 4

Array#map works (documentation)

const getFromIndex = (array, indexes) => indexes.map((index) => array[index]);

You can use Array#filter too (documentation)

const fruitier = ['apple', 'orange', 'grapes', 'pineapple', 'fig',   'banana', 'jackfruit', 'pomegranate'];
const indexArr = [0, 2, 4];  

const getFromIndex = (array, indexes) => {
  return array.filter((element, index) => indexes.includes(index)); 
};

Or also Array#reduce (documentation)

const getFromIndex = (array, indexes) => {
    return indexes.reduce((result, i) => result.concat(array[i]), []); 
};

Solution 5

Use lodash pullAt

var fruitier = ["apple", "orange", "grapes", "pineapple", "fig", "banana", 
"jackfruit", "pomegranate"];
var indexArr = [0, 2, 4];
var resultArr = _.pullAt(fruitier, indexArr);
console.log(resultArr);
// ["apple", "grapes", "fig"]

<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

Key difference to be aware of alongside the above recommendation for _.at() is - this method mutates input array.

Share:
14,581

Related videos on Youtube

Sathya
Author by

Sathya

Well-qualified Front-End Developer familiar with a wide range of programming utilities and languages. Knowledgeable of frontend and backend development requirements. Able to handle any part of the process with ease. Collaborative team player with excellent technical abilities offering 9+ years of related experience.

Updated on September 15, 2022

Comments

  • Sathya
    Sathya over 1 year

    I have a set of two arrays. One contains some fruit values as strings, the other one contains some random numbers. Here I considered the number arrays are the indexes of the fruits array. How to get a new array of fruits given the numbers in the index array?

    Sample code:

    var resultArr = [];
    var fruitier = ["apple", "orange", "grapes", "pineapple", "fig", "banana", "jackfruit", "pomegranate"];
    var indexArr = [0, 2, 4];
    

    Output:

    resultArr = ["apple", "grapes", "fig"];
    
  • elquimista
    elquimista about 5 years
    Just be aware that if you use flow type, it will complain because _.at() expects the first argument to be of Object, not Array. I think it's fine to ignore it using // $FlowFixMe