-1

I saw this piece of code inside a JS book, but don't quite understand what is happening. Can someone explain it?

var values = [ 213, 16, 2058, 54, 10, 1965, 57, 9 ];
values.sort(function(value1,value2){ return value2 - value1; });

It seems like the sort is just taking in the difference of 2 values, yet it returns the sorted array. What is happening behind the scene?

guest
  • 2,185
  • 3
  • 23
  • 46
  • Take a look to [this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) – isvforall Apr 20 '16 at 19:31

2 Answers2

0

If you just had this code:

var values = [ 213, 16, 2058, 54, 10, 1965, 57, 9 ];
values.sort();

Then the values would be sorted using a default comparison function. You would end up with them sorted alphabetically with each value in the array treated as a string.

When you pass a function as a parameter to the sort function then it will sort according to that function. For any two values it will swap them according to whether the return value is a positive or negative value. Specifically (according to MDN):

  • If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.
  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  • If compareFunction(a, b) is greater than 0, sort b to a lower index than a.
  • compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.

Using a difference function is convenient if and only if you can guarantee that all values are numbers and that the difference never overflows. The provided comparison function will sort the array in descending order.

Octopus
  • 8,075
  • 5
  • 46
  • 66
0

You can have a look in mozilla developer documentation, there are many examples sort

Borja Tur
  • 779
  • 1
  • 6
  • 20
  • i've already seen that. thank you. I'm really asking what's special about this comparator function for this to sort properly. – guest Apr 24 '16 at 20:59