简体   繁体   中英

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!

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.

A solution with sorting with map .

 function sort(string) { var array = string.split(' '), mapped = array.map(function (a, i) { return { index: i, value: +a.split('').reduce(function (a, b) { return +a + +b; }) }; }); return mapped.sort(function (a, b) { return a.value - b.value; }).map(function (a) { return array[a.index]; }).join(' '); } document.write('<pre>' + JSON.stringify(sort('100 54 32 62'), 0, 4) + '</pre>'); 

I would have an array of indexes (0..n-1) and sort it based on the weights array (by passing a comparison function that compares the weights for the given index values). Then You will have an array of indexes, which show where each item should be (in your example the index array would be [0, 2, 3, 1] which means that arr[0] should be first, then arr[2], etc. So now you can build the sorted array using the index array, for example [arr[0], arr[2], arr[3], arr[1]]. So to recap: Get the input array, compute weights array, create index array 0..n-1, sort it based on the weights array, and finally construct the output array based on the sorted index array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM