Kimberly - 1 year ago 120
Javascript Question

# How to create a for loop for an array with multiple elements?

I'm a student studying JavaScript so my knowledge isn't complex, so please be gentle. :)

I have been given:

``````var region1 = [1540, 1130, 1580, 1105];
var region2 = [2010, 1168, 2305, 4102];

var region3 = [2450, 1847, 2710, 2391];

var region4 = [1845, 1491, 1284, 1575];

var region5 = [2120, 1767, 1599, 3888];
``````

Each number in the bracket represents the numbers of the quarter. I need to give for loops that sum up the sales for each region (addition across) and for each quarter (addition down the column). I understand how to do single item arrays. For example:

``````var sum=0;
for (var i = 0; i < totals.length; i++) {
sum += totals [i];
}
``````

Thank you in advanced.

Answer Source

I am not sure if this what you are after, but I presume you want the total sales for a quarter in all the five regions;

``````var regions = {
region1:[1540, 1130, 1580, 1105],
region2:[2010, 1168, 2305, 4102],
region3:[2450, 1847, 2710, 2391],
region4:[1845, 1491, 1284, 1575],
region5:[2120, 1767, 1599, 3888]
};

var totalPerRegion = 0,
quarter1 = 0,
quarter2 = 0,
quarter3 = 0,
quarter4 = 0;

for(region in regions){
// calculate the sales per quarters;
quarter1 += regions[region][0];
quarter2 += regions[region][1];
quarter3 += regions[region][2];
quarter4 += regions[region][3];
}

console.log('quarter 1:', quarter1);
console.log('quarter 2:', quarter2);
console.log('quarter 3:', quarter3);
console.log('quarter 4:', quarter4);``````

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download