2

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.

Magofoco
  • 5,098
  • 6
  • 35
  • 77
  • 4
    [Why is using “for…in” with array iteration a bad idea?](https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea) – Andreas Nov 09 '19 at 16:56
  • your solution seems ok to me – PA. Nov 09 '19 at 16:57

2 Answers2

6

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)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

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)
   
Shubham Verma
  • 4,918
  • 1
  • 9
  • 22