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

Time:10-22

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!

CodePudding user response:

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)))

CodePudding user response:

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();
  • Related