I'm at my wit's end when it comes to adding up the individual sums of arrays inside a two-dimensional array. For example:
var arrArrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
function sumArray(numberArray) {
var sum = 0;
numberArray.forEach(function(a,b) {
sum = a + b;
});
return sum;
}
The function sumArray can successfully add up & return the sum of a regular (one-dimensional array), but when passed arrArrays it returns a single array of random-looking values.
I would need it to be able to return the sums of however many arrays are inside another array. The reason being is because I need this next function to 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 the arrays based on the sum of the numbers inside each array (descending from highest to lowest).
Any tips would be awesome. Thank you in advance!
bis the index. - Matt Burland"7,8,92". - Travis JsumArray, but an array of numbers. Or are you passing an array of arrays of arrays of numbers tosumSort? - Felix KlingsumArray(because that's whatarrArrayscontains), not an array of arrays. Why do you thinksumSortdoes not work? I mean there are issues as already mentioned.forEachdoesn't work like that and your sort callback never returns1. Your sort callback basically says "ifsumArray1is not smaller thansumArray2, then they are equal", which is certainly not the case forsumArray1 = 30andsumArray2 = 10. Have a look at developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… . - Felix Kling