Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort one array based on how another gets sorted? (Javascript)

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!

like image 294
joh04667 Avatar asked Sep 25 '22 21:09

joh04667


1 Answers

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.

like image 101
Will Avatar answered Sep 29 '22 01:09

Will