Search code examples
javascriptfor-loopnested

Nested for loop does not iterate correctly


I have two strings which I split and want to iterate through, and use the value in an IF statement. However, when I print the values the output is not correct (it prints the values multiple times).

Desired output: So basically, in the first iteration of loop I would like to have BMW and car1 as the values. Moreover, going into the IF statement this would mean that the variable year is set to 1999.

<!DOCTYPE html>
<html>
<body>

<script>
var input = "BMW Volvo Saab";
var brand = input.split(" ");
var brandOut = "";
var i;


var input2 = "car1 car2 car3";
var car = input2.split(" ");
var carOut = "";
var j;



for (i = 0; i < brand.length; i++) {
    for (j = 0; j < car.length; j++) {
    brandOut += brand[i];
    carOut += car[j];


//document.write(brandOut);
//document.write(carOut);

if (carOut == 'car1'){
    var year = "1999"

} else if (carOut == 'car2'){
    var year = "2000"

} else {
    var year = "2001";
}


//do something with the current value of year for each iteration of the loop

    }
}

</script>

</body>
</html>

Solution

  • Per your comment:

    I aim to get BMW car1, Volvo car2, SAAB car3

    The loop and creation of the new list can be done using .map(). We loop through list of brands, and grab the same index item from car. We then combine the two values into a single string: (brand) (car). The result is a new array with a list of brands and cars.

    var input = "BMW Volvo Saab";
    var brand = input.split(" ");
    
    var input2 = "car1 car2 car3";
    var car = input2.split(" ");
    
    var brandCars = brand.map((item,index) => `${item} ${car[index]}`);
    console.log(brandCars);