Home > Net >  Distribute elements of array to the other elements of the array in JavaScript
Distribute elements of array to the other elements of the array in JavaScript

Time:10-20

I've been trying for a few days to wrap my head around this problem. I need to create an array of array pairs distributed evenly amongst elements. Here's my initial array...

const groups = [
   {
       name: "Sizes",
       options: [{ name: "small" }, { name: "medium" }, { name: "large" }]
   },
   {
       name: "Colors",
       options: [{ name: "red" }, { name: "blue" }]
   },
]

And here's my desired output...

[
   [ 'small', 'red' ],
   [ 'small', 'blue' ],
   [ 'medium', 'red' ],
   [ 'medium', 'blue' ],
   [ 'large', 'red' ],
   [ 'large', 'blue' ]
]

I'm able to hard-code it like so...

const masterArr = [];


const options = [];

options.push(groups[0].options[0].name)
options.push(groups[1].options[0].name)


masterArr.push(options)


const options2 = []

options2.push(groups[0].options[0].name)
options2.push(groups[1].options[1].name)


masterArr.push(options2)


const options3 = []

options3.push(groups[0].options[1].name)
options3.push(groups[1].options[0].name)

masterArr.push(options3)


const options4 = []

options4.push(groups[0].options[1].name)
options4.push(groups[1].options[1].name)

masterArr.push(options4)


const options5 = []

options5.push(groups[0].options[2].name)
options5.push(groups[1].options[0].name)

masterArr.push(options5)


const options6 = []

options6.push(groups[0].options[2].name)
options6.push(groups[1].options[1].name)

masterArr.push(options6)


console.log(masterArr)

I know it's crude, but it's how I approach visualizing a problem then figuring out how to refactor using the appropriate methods, but I can't seem to tackle this one.

Any help is greatly appreciated!

CodePudding user response:

You have to use a nested for loop

const groups = [
   {
       name: "Sizes",
       options: [{ name: "small" }, { name: "medium" }, { name: "large" }]
   },
   {
       name: "Colors",
       options: [{ name: "red" }, { name: "blue" }]
   },
]

var res = [];
var numOfSizes = groups[0].options.length;
var numOfColors = groups[1].options.length;

for (let sizeIdx=0; sizeIdx<numOfSizes; sizeIdx  ) {
    for (let colorIdx=0; colorIdx<numOfColors; colorIdx  ) {
        let size = groups[0].options[sizeIdx].name;
        let color = groups[1].options[colorIdx].name;
        res.push([size, color]);
    }
}
console.log(res);
I've editted my post to use simple for loops with indices, as it seems like you're still learning the basics and I want to keep things simple :)

  • Related