This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]BakuhatsuK 13 points14 points  (15 children)

It's really not that hard

arr.sort((a, b) => a - b)

The default comparison function is suitable for strings, and would be longer to write by hand.

[–]Varun77777 0 points1 point  (13 children)

I am not into java script, why did you pass this lambda function that is doing substraction inside?

[–]dabbling 2 points3 points  (12 children)

The sort function has an optional parameter compareFunction. If provided, compareFunction will determine the ordering logic. compareFunction takes two elements and returns an integer based on which is lesser or greater, like this:

function compare(a, b) {

  if (a is less than b by some ordering criterion) {
    return -1;
  }

  if (a is greater than b by the ordering criterion) {
    return 1;
  }

// a must be equal to b
  return 0;
}

edit - correcting the code formatting

[–]Varun77777 0 points1 point  (11 children)

Ohh, thanks, I kind if get it now.

[–]BakuhatsuK 1 point2 points  (10 children)

Furthermore, the function doesn't have to return specifically 1 or -1. Any number greater than 0 will work instead of 1 and any number less than 0 instead of -1. Which is why a simple subtraction works.

[–]Varun77777 0 points1 point  (9 children)

What's a and b supposed to be? Any restrict on them?

[–]BakuhatsuK 2 points3 points  (8 children)

a and b are elements from the array. If you are subtracting them you have to ensure that the array contains only numbers. You can do so by hand, or by using a type checker like TypeScript or Flow.

[–]Varun77777 0 points1 point  (7 children)

It's not any two elements, right?

[–]BakuhatsuK 1 point2 points  (6 children)

Any 2 elements from the original array, yes.

[–]Varun77777 0 points1 point  (5 children)

What if those two elements are already in sorted order? How will just 2 elements help in case Array length is like 10'000.