I have to create a function to sort a string of numbers based on the 'weight' of each number--the 'weight' is the digits of the numbers added together (the weight of 99 would be 18, the weight of 100 would be 1, etc etc). This means that a string "100 54 32 62"
would return "100 32 62 54"
.
I can get an array of the weights of these numbers just fine by using:
function orderWeight(str) {
var arr = str.split(" ");
var sortArr = [];
arr.forEach(t => sortArr.push(t.split("").map(s => parseInt(s, 10)).reduce(add, 0)));
}
where add
is just a generic addition function. For the above example, sortArr
would be [1, 9, 5, 8]
.
What's the best way to sort the array of the original numbers from the string arr
based on how the new array of the number weights sortArr
gets sorted?
Thanks!
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:
Per suggested by Sterling, here's the same function written 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 writing Javascript using lambda syntax. Thanks to Sterling for suggesting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With