我有一组两个数组。一个包含一些水果值作为字符串,另一个包含一些随机数。在这里我认为数字数组是fruits数组的索引。如何根据索引数组中的数字获得一个新的水果数组?
示例代码:
var resultArr = [];
var fruitier = ["apple", "orange", "grapes", "pineapple", "fig", "banana", "jackfruit", "pomegranate"];
var indexArr = [0, 2, 4];
输出:
resultArr = ["apple", "grapes", "fig"];
答案 0 :(得分:21)
使用.map
:
var resultArr = indexArr.map(i => fruitier[i])
答案 1 :(得分:9)
如果您想使用lodash实现这一目标,请使用_.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>
答案 2 :(得分:5)
for(var i = 0; i < indexArr.length; i++)
resultArr.push(fruitier[indexArr[i]]);
答案 3 :(得分:1)
您可以使用for..of
循环
for (var key of indexArr) resultArr[resultArr.length] = fruitier[key];
答案 4 :(得分:1)
数组#map工作(documentation)
const getFromIndex = (array, indexes) => indexes.map((index) => array[index]);
您也可以使用Array#filter(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));
};
或者数组#reduce(documentation)
const getFromIndex = (array, indexes) => {
return indexes.reduce((result, i) => result.concat(array[i]), []);
};
答案 5 :(得分:1)
使用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>
在上面针对_.at()的建议中要注意的主要区别是-该方法会改变输入数组。