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.

2

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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)
   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.