javascript - Sum of individual arrays inside two-dimensional array -


i'm @ wit's end when comes adding individual sums of arrays inside two-dimensional array. example:

var arrarrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];  function sumarray(numberarray) {   var sum = 0;   numberarray.foreach(function(a,b) {     sum = + b;   });   return sum; } 

the function sumarray can add & return sum of regular (one-dimensional array), when passed arrarrays returns single array of random-looking values.

i need able return sums of many arrays inside array. reason being because need next function call sumarray():

function sumsort(arrayofarrays) {   arrayofarrays.sort(function(a,b) {     var sumarray1 = sumarray(a);     var sumarray2 = sumarray(b);     if (sumarray1 < sumarray2) {       return -1;     } else {       return 0;     }   }); } 

sumsort() will, theoretically, order arrays based on sum of numbers inside each array (descending highest lowest).

any tips awesome. thank in advance!

this method allow handle arrays of nested depth. first you'll flatten inner arrays , sum them usual. if want handle non-nested arrays, can add check on first level, shown in question.

var arrs = [[[[1]], [2, 3]], [4, 5, 6], [7, 8, 9]]; //https://stackoverflow.com/a/15030117/1470607 function flatten(arr) {     return arr.reduce(function(flat, arr) {         return flat.concat(array.isarray(arr) ? flatten(arr) : arr);     }, []); }; var sums = arrs.map(function(arr) {     return flatten(arr).reduce(function(sum, item) {         return sum + item;     }); }); //[6, 15, 24] 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -