JavaExplorer
JavaExplorer

Reputation: 33

How to duplicate indexes in array with numbers of second array, resulting third array in JS

I have an array of products amount, and another array of products ID's.

I'm trying to do something like this:

arrayOfAmount = [2,3,4]

arrayOfId = [1,2,3]

resulting the third array of ID's:

arrayOfProducts = [1,1,2,2,2,3,3,3,3]

how can I do that?

thank you in advance!

Upvotes: 0

Views: 37

Answers (2)

Apollo79
Apollo79

Reputation: 704

Here is a version how you could do this using the map and flat and fill methods of arrays. I added some comments to help understanding what the code does:

const arrayOfAmount = [2, 3, 4];

const arrayOfId = [1, 2, 3];

const arrayOfProducts = arrayOfId.map((id, index) => {
    // get how often an id should be in the array
    const length = arrayOfAmount[index];

    // create an array with the length
    const array = Array(length);

    // insert the ID to every index of the array
    return array.fill(id);
  })
  // and finally flat, so that the array doesn't look like: [[1, 1], [2, 2, 2], [3, 3, 3, 3]]
  .flat();

console.log(arrayOfProducts);

A short version would be:

const arrayOfAmount = [2, 3, 4];

const arrayOfId = [1, 2, 3];

const arrayOfProducts = arrayOfId.map((id, index) => Array(arrayOfAmount[index]).fill(id))
  .flat();

Upvotes: 1

Giorgi Moniava
Giorgi Moniava

Reputation: 28654

You can try this:

let arrayOfAmount = [2,3,4]

let arrayOfId = [1,2,3]

console.log(arrayOfId.flatMap((x,i)=>Array(arrayOfAmount[i]).fill(x)))

Upvotes: 1

Related Questions