var originalArray = [
[{value: 2}, {value: 3}],
[{value: 11}],
[{value: 1}, {value: 2}, {value: 3}, {value: 4}]
];
var sortedArray = originalArray.sort(function(row1, row2) {
add = function(a, b) {return a + b.value};
return row1.reduce(add, 0) - row2.reduce(add, 0);
});
console.log(sortedArray);
Let's break this down, shall we?
We start with the original array:
var originalArray = [
[{value: 2}, {value: 3}],
[{value: 11}],
[{value: 1}, {value: 2}, {value: 3}, {value: 4}]
];
Then we sort it. Let's work from the inside out. First, how do we calculate the sum of a row? We can use the reduce function:
exampleRow = [{value: 2}, {value: 3}];
add = function(a, b) {return a + b.value};
console.log(exampleRow.reduce(add, 0));
The reduce function takes in another function (add in this case) and uses it to iterate over an array and reduce it to a single item (usually a number). reduce needs a function that takes in two arguments - the running total, and the next item. Reduce roughly does the following:
array.prototype.reduce = function(fn, initial) {
runningTotal = initial;
for (var i = 0; i <= array.length; i++) {
runningTotal = fn(runningTotal, array[i]);
}
return runningTotal;
}
In words, it starts with the initial value, and then runs your function over and over, with each run using the last run's output and the next item in the array.
In our case, the fn function is add:
add = function(a, b) {return a + b.value};
add is very simple; it takes the running total (a) and adds the value of the next item (b). Over the entire array, this simplifies to 0 + array[0].value + array[1].value + ... + array[array.length-1].value - the sum of the array.
We're almost there! The last part is the actual sorting. We do this with the sort function (surprise!). The sort function also takes in a function with two arguments that it uses to iterate over the array. The function you give to sort, however, has to return a number. sort uses this function to compare the two arguments; if the output is positive, the first item is 'bigger', while if the output is negative, the second item is 'bigger'. (If the output is zero they are equal.) sort uses this to sort the array in ascending order.
In our case, our function takes in the two rows and returns the sum of the first minus the sum of the other. This means that if the first row's sum is greater ist will be later in the array and vice versa.
MyArray.sort((a, b) => b.reduce((s, o) => s + o.value, 0) - a.reduce((s, o) => s + o.value, 0));MyArraywhile only n such summations are necessary.