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

I need 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 (weight 99 will be 18, weight 100 will be 1, etc. Etc.). This means that the string "100 54 32 62" will return "100 32 62 54" .

I can get an array of weights of these numbers just fine 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 general addition function. In the above example, sortArr will be [1, 9, 5, 8] .

What is the best way to sort an array of source numbers from a string arr based on sorting a new array of weights sortArr ?

Thanks!

+5
source share
3 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:

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.

+4
source

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>'); 
0
source

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

-1
source

Source: https://habr.com/ru/post/1238885/


All Articles