I have two arrays:
1- inventory that contains some elements
2- indices_dates that contains the indices of the elements I want from inventory.
Is there a simple way to create an array formed by the elements of inventory if their index is contained into indices_dates
Example:
let inventory
let indices_dates
let final = []
inventory = [25, 35, 40, 20, 15, 17]
indices_dates = [0, 2, 3, 5]
---Some Code To Get Final Array---
The output I would like:
final = [25, 40, 20, 17]
I did the following:
let inventory
let indices_dates
let final = []
let i
inventory = [25, 35, 40, 20, 15, 17]
indices_dates = [0, 2, 3, 5]
for (i in indices_dates) {
final.push(inventory[indices_dates[i]])
}
But I am wondering if there is another, more direct way to achieve it.
-
4Why is using "for...in" with array iteration a bad idea?Andreas– Andreas2019年11月09日 16:56:46 +00:00Commented Nov 9, 2019 at 16:56
-
your solution seems ok to mePA.– PA.2019年11月09日 16:57:08 +00:00Commented Nov 9, 2019 at 16:57
2 Answers 2
You can use Array.map() to iterate the indices array, and take the values from inventory:
const inventory = [25, 35, 40, 20, 15, 17]
const indices_dates = [0, 2, 3, 5]
const final = indices_dates.map(idx => inventory[idx])
console.log(final)
Comments
You can do as @Ori suggest or alternative solution is :
Another approach is using forEach :
const inventory = [25, 35, 40, 20, 15, 17]
const indices_dates = [0, 2, 3, 5];
let final = [];
indices_dates.forEach(data => final.push(inventory[data]))
console.log(final)
Using for of :
const inventory = [25, 35, 40, 20, 15, 17]
const indices_dates = [0, 2, 3, 5];
let final = [];
for (let dateIndex of indices_dates){
final.push(inventory[dateIndex])
}
console.log(final)