Magofoco
Magofoco

Reputation: 5446

Get elements from an array based on array containing indices

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.

Upvotes: 2

Views: 49

Answers (2)

Shubham Verma
Shubham Verma

Reputation: 5054

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)
   

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191976

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)

Upvotes: 6

Related Questions