medev21
medev21

Reputation: 3051

can someone explain how javascript sort method works?

I have encountered this javascript code involving a sort method with a custom return.

const nums =  ['9', '5', '3', '34', '30' ];
const num = nums.map(n => n.toString()).sort((a,b) => a + b < b + a? 1: -1).join('')

Essentially, this code is returning the largest possible integer. I have the basic knowledge of sort, if you want the numbers in ascending order then you'll use a-b for the return. If descending is desired, then you would use b-a.

I want to know how the a and b are working behind the scenes. I couldn't find a source where it explains in details how the sort works. I would like to know step by step when the sort is in action; it will give me a better a idea how the code above works.

Your help will be appreciated.

Upvotes: 0

Views: 91

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386883

You yould take a little different callback which adds the two values in different order and returns the delta of both.

It works by getting a part string of the final result and changes the order for getting the greatest value of both items.

For example, the given data sorts in EDGE in this order:

 a   b  b + a  a + b  delta  comment       array
--  --  -----  -----  -----  -------  --------------
                                       3  5  9 30 34
 3   5     53     35    -18  switch    5  3  9 30 34
 3   9     93     39    -54  switch    5  9  3 30 34
 5   9     95     59    -36  switch    9  5  3 30 34
 3  30    303    330     27  keep      9  5  3 30 34
30  34   3430   3034   -396  switch    9  5  3 34 30
 5  34    345    534    189  keep      9  5  3 34 30
 3  34    343    334     -9  switch    9  5 34  3 30

const
    array = ['3', '5', '9', '30', '34'],
    result = array.sort((a, b) => (b + a) - (a + b)).join('');

console.log(...array);
console.log(result);

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075875

Details can be found in the spec. Basically, sort works by calling the callback repeated to compare two entries from the array. The callback is supposed to return -1 if a is "less than" b (according to whatever rules that particular callback wants to apply for what "less than" means), 0 if they're the same, or 1 if a is "greater than" b. It continues doing that, with different pairs of entries from the array, until it's sorted the array.

How sort does that is up to the implementation, it's not dictated in the spec. All the spec dictates is the paragraph above, and that (as of quite recently) the sort must be stable.

A couple of notes on the specific code you've shown:

  • arr should be nums in the first line
  • There's no point to the map call, the entries in the array are already strings
  • The comparisons it's doing are alphabetic
  • The sort method is incorrectly coded, because if a and b are the same, it returns -1, not 0

Upvotes: 1

Related Questions