-1

I'm trying to list all combinations of strings from 3 arrays, and assign all of those combinations to separate variables. I'm able to do it with only two arrays, but not with three for a reason I don't know. This is the code:

var i = 0;
for (var wall of [
    "red walls",
    "blue walls",
    "green walls",
    "pink walls",
    "purple walls",
    "gray walls",
    "white walls"]) {
    for (var floor of [
        "carpet floor",
        "oak-wood floor",
        "spruce-wood floor",
        "acacia-wood floor",
        "birch-wood floor"]) {
        for (var accessory of [
            "no accessory",
            "open window",
            "closed window"])
            var room = [];
            room[i] = {
                wall: wall,
                floor: floor,
                accessory: accessory
            };
            console.log("Room " + i + " - " + room[i].wall + ", " + room[i].floor + ", " + 
room[i].accessory);
            ++i;
    }    
}

Every time I run the code, it works perfectly, except for the last part of the code: the 3rd array. The accessory property always shows up as the last string of the accessory variable (closed window). I have no idea what to do, or what could fix this problem.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Junior
  • 3
  • 2
  • 1
    You don’t have the curly brackets of the innermost loop. And why isn’t the array declared at the beginning? – RatajS Nov 06 '21 at 21:38
  • 1
    Does this answer your question? [Cartesian product of multiple arrays in JavaScript](https://stackoverflow.com/questions/12303989/cartesian-product-of-multiple-arrays-in-javascript) – fen1x Nov 06 '21 at 21:39
  • Better to have variables for list of walls, floors, and accessories than to inline the lists like you have. – jarmod Nov 06 '21 at 21:42

1 Answers1

0

I rewrited a little bit your code. I think it will work right now

var walls = [
    "red walls",
    "blue walls",
    "green walls",
    "pink walls",
    "purple walls",
    "gray walls",
    "white walls"
];

var floors = [
    "carpet floor",
    "oak-wood floor",
    "spruce-wood floor",
    "acacia-wood floor",
    "birch-wood floor"
]
var accessories = [
    "no accessory",
    "open window",
    "closed window"
]

var i = 0;
for (var wall of walls) {
    for (var floor of floors) {
        for (var accessory of accessories) {
            console.log("Room " + i + " - " + wall + ", " + floor + ", " + accessory);
            ++i;
        }
    }
}
Lahcen
  • 1,231
  • 11
  • 15