How To Get An Array Of Values Based On An Array Of Indexes?
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
Solution 1:
Use .map
:
let resultArr = indexArr.map(i => fruitier[i])
Solution 2:
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);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script>
Solution 3:
for(var i = 0; i < indexArr.length; i++)
resultArr.push(fruitier[indexArr[i]]);
Solution 4:
Array#map works (documentation)
constgetFromIndex = (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];
constgetFromIndex = (array, indexes) => {
return array.filter((element, index) => indexes.includes(index));
};
Or also Array#reduce (documentation)
constgetFromIndex = (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/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.
Post a Comment for "How To Get An Array Of Values Based On An Array Of Indexes?"