This should do the trick:
var x = '100 54 32 62'; function orderWeight(str) { return str.split(' ').sort(function(a, b) { return (a.split('').reduce(function(p, c) { return +p + +c; })) > (b.split('').reduce(function(p, c) { return +p + +c; })); }).join(' '); } var result = orderWeight(x);
Output:
100 32 62 54
UPDATE:
At the suggestion of Stirling, here is the same function recorded in lambda format.
var x = '100 54 32 62'; function orderWeight(str) { return str.split(' ').sort((a, b) => a.split('').reduce((p, c) => +p + +c) > b.split('').reduce((p, c) => +p + +c)).join(' '); } var result = orderWeight(x);
Note. This is my first time I wrote Javascript using lambda syntax. Thanks to Sterling for the suggestion.
source share