Skip to content Skip to sidebar Skip to footer

Combine And Sum The Values In Multiple Arrays

All the relevant code is provided here http://jsfiddle.net/DuWGj/ , as well as print(appendTo) statements. To keep it short, I'm making 4 arrays. Each array has 4 numbers. Then I c

Solution 1:

What is happening

After running:

prePickNumbers(four, 4, 40, 20, 1);

...the value of four.myArraysCombined is:

[[[2, 17, 20, 1], [7, 2, 20, 11], [7, 14, 3, 16], [12, 17, 3, 8]]]

In other words, it is not the result that you claim it is. You should verify that you have the result that you think you do at each step of the process, before moving on. As it stands, you do not have a flattened array. You need to fix that first and then move on to iterating and summing.

Why this is happening

The reason for the final structure starts at the following line in prePickNumbers:

tempMyArraysCombined.push(objName.myArray[x]);

You're pushing an array into another array each time, so the result after the loop is an array of arrays. But, then, you push that result into another array:

objName.myArraysCombined.push(tempMyArraysCombined);

So the final result is actually an array containing an array of arrays (notice the extra set of brackets in the output above). The problem is that you're pushing an entire array into your output at each step in the process, which is creating a nested mess. You should be pushing elements of each array, not the arrays themselves.

How to fix it

Here is one possible solution. Replace prePickNumbers with the following function:

functionprePickNumbers(objName, theNum, theSumNum, theMaxNum, theMinNum) {
    var tempMyArraysCombined = [];
    for (var x = 0; x < theNum; x += 1) {
        pickNumbers(objName.myArray[x], theNum, theSumNum, theMaxNum, theMinNum);
        for (var j = 0; j < objName.myArray[x].length; j++) {
            objName.myArraysCombined.push(objName.myArray[x][j]);
        }
    }
}

Solution 2:

You may want to try

 total += four.myArraysCombined[0][x]

Solution 3:

I extract this from you fiddle:

functionprePickNumbers(objName, theNum, theSumNum, theMaxNum, theMinNum) {
    var tempMyArraysCombined = [];
    for (var x = 0; x < theNum; x += 1) {
    pickNumbers(objName.myArray[x], theNum, theSumNum, theMaxNum, theMinNum);
    tempMyArraysCombined.push(objName.myArray[x]);
    }
    objName.myArraysCombined.push(tempMyArraysCombined); 
}

edit the last line to:

functionprePickNumbers(objName, theNum, theSumNum, theMaxNum, theMinNum) {
    /* your code */
    objName.myArraysCombined=tempMyArraysCombined; //edit this line not push() but =
}

now there are no "UNDEFINED" in output html. :)

Post a Comment for "Combine And Sum The Values In Multiple Arrays"