Note that there are some explanatory texts on larger screens.

plurals
  1. POAdd specific values of multidimensional array together Javascript
    text
    copied!<p>Okay, so I have a multidimensional array that itself contains 9 arrays. Each of these nested arrays contains 10 numeric values. For sake of simplicity, let's say it all looks like this:</p> <pre><code>var MyArray = [ [1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10] ] </code></pre> <p>I am trying to write a function that will take the first index of each nested array (in this case, all 1's) and add them together, pushing this value either to an array or an object. Then, I need this function to continue on, adding all the values of the next index, and the next, and so on and so forth. In the end, I should have an array of 10 values (or an object works here as well). The values would be:</p> <pre><code>1+1+1+1+1+1+1+1+1, 2+2+2+2+2+2+2+2+2, 3+3+3+3+3+3+3+3+3... </code></pre> <p>...and so on so forth, so that the actual values of the new array would be this:</p> <pre><code>[9, 18, 27, 36, 45, 54, 63, 72, 81] </code></pre> <p>The catch here is that I need this to by flexible/dynamic, so that it will work in case MyArray has only 6 arrays, or maybe the nested arrays have only 4 values each. It should work with any amount of nested arrays, each with their own amount of values (though each nested array will contain the SAME amount of values as one another!).</p> <p>What would be the best way to accomplish this via JavaScript and/or jQuery? Note that I could also have the values output to an object, in this fashion:</p> <pre><code>{1:9, 2:18, 3:27, 4:36, 5:45, 6:54, 7:63, 8:72, 9:81} </code></pre> <p>I tried using similar code to this from another StackOverflow thread to get an object, but it is returning</p> <pre><code>{1:NaN, 2:NaN, 3:NaN, etc.} </code></pre> <p>That thread can be found here:</p> <p><a href="https://stackoverflow.com/questions/10487970/javascript-multidimensional-array-add-values">Javascript Multidimensional Array: Add Values</a></p> <p>I'm using the "underscore" method and the jQuery $.each part of it provided by Otto.</p> <p>Anyone able to help here??</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload