0

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.

7
  • 1
    The following links should help: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…, developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Oct 31, 2019 at 14:39
  • 1
    what is nums? i s it arr? Commented Oct 31, 2019 at 14:39
  • Your compare callback doesn't make any sense. The return value will always be -1 Commented Oct 31, 2019 at 14:41
  • 2
    In this case a + b is string concatenation not arithmetical operation and the sort function is ordering the elements alphabetically not numerically (111 will be before 2) Commented Oct 31, 2019 at 14:42
  • 1
    Ah, right... concatenation, not addition. That was really bugging me. Commented Oct 31, 2019 at 14:43

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

4 Comments

Didn't know the specification was updated to require stability in the implementation, nice detail.
@PatrickRoberts - Thanks. :-) Writing my book, I have to be fairly clued in to changes. :-)
(I might actually suggest that book as my next Christmas gift, hope you can get it published before then edit January 9th... maybe a late Christmas gift then)
@PatrickRoberts - Yeah, I blew it on making it in time for Christmas. :-(
0

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);

2 Comments

thanks for providing the example, i like visual explanations. The one thing I'm still puzzled. So you go from 3 to 5, then 3 to 9, but I'm not sure why you went from 5 to 9 instead of from 3 to 30.
it is not me, it is the implementation which is not defined in the language specification (ECMA Script). the vendor of the user agent puts it's own algorithm for sorting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.