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

杀马特。学长 韩版系。学妹 提交于 2019-11-30 13:04:38
for(var i = 0; i < indexArr.length; i++)
  resultArr.push(fruitier[indexArr[i]]);

Use .map:

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

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>

You can use for..of loop

for (var key of indexArr) resultArr[resultArr.length] = fruitier[key];

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]), []); 
};

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/lodash@4.17.11/lodash.min.js"></script>

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!