Skip to content
Advertisement

Create duplicate arrays based on a column value

I have the following array, the first item in the array has a quantity of 3 while the rest has a quantity of 1. These numbers are dynamic.

JavaScript

How can I change that to the following output? So the first item that did have a quantity of 3 is now separated out into 3 array items and the quantity set to one for each?

JavaScript

Advertisement

Answer

You can loop over the original arr and push the contents to a second array. If the quanity > 1 you can create a loop that pushes the item for each quanity. Something like this:

JavaScript

Note that the code expects your original array to be called $arrA

Edit: removed the if/else as suggested in the comments

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement