Sort Arrays with sort explanation?

var array = [1, 12, 21, 2];

// Only change code below this line.

array.sort(function(a,b){
  return b - a;
});

I finished the challenge but I don’t totally understand the concept. How does returning b - a necessarily return the array in largest to smallest order? I am having a difficult time understanding how the array is handled in the function.

1 Like

Your post inspired me to play around this a little. What I think is happening is that callback, the compare function, is passed each pair of numbers until it iterates through the entire array. So starting with function(1,12), the result would be -11, which would shift the 1 to the next position in the array. Next up it would call function(1,21) and shift it. Anytime the callback returns a negative number, it shifts A further down the array.

var array = [1, 12, 21, 2];

// Only change code below this line.

array.sort(function(a,b){
  return b - a;
});

//First Iteration:
[12, 1, 21, 2];

//Second Iteration:
[12,21,1,2]

//Third Iteration:
[12,21,2,1]

//Fourth Iteration:
[21,12,2,1]


So if you wanted to sort the array ascending, you would edit your compare function as follows:

array.sort(function(a,b){
  return a - b;
});

Again, this is me just speculating. I tried to look up the documentation and there isn’t a lot.


https://www.w3schools.com/jsref/jsref_sort.asp

1 Like

The sort() function is a little odd.

I’m assuming that it does a bubble sort - it iterates through the array and if one element is larger than the previous, it swaps them. It keeps looping through the array until no changes are made - i.e., the array is sorted. (I’m guessing that it’s a bubble sort - it could be something else - the result is the same.)

The “problem” with doing numbers is that sort assumes that you are doing strings, so it thinks that “142” is “lower” than “9”. Useful if you’re alphabetizing strings, but not for numbers.

That is what sort() assumes. By providing a function, you are overriding it’s comparison function and giving it a new one. You are saying “The standard sort() comparison techniques doesn’t work for me, so I’m providing my own.” When it evaluates that function, it compares the current element (a) with the next element (b). If the function returns a positive number, then sort() swaps the values. If it returns a 0 or a negative number then those two elements are in the right order so it leaves them alone. It keeps looping though the values until no changes are made.

Would it make more sense if we wrote it like this?

array.sort(function(currentValue, nextValue) {
  if (nextValue > currentValue) {
		return 1; // swap these values
	} else {
		return -1; // leave alone (could return 0, no diff)
	}
});

The if could return any positive number and the else could return 0 or any negative number - it doesn’t change how sort() will respond - positive numbers mean that they are out of the order that you are defining, negatives mean that they are in the order that you are defining. (You could have a much more complicated function, like if you wanted a complicated sort order for objects, based on the relationships of multiple values in those objects.)

Writing it the below way accomplishes the same exact thing:

array.sort(function(a,b){
  return b - a;
});

Yes, it’s weird. I’m not new to programming but am new to JS so this was a weird thing for me too, but it does makes sense once you dig into it.

1 Like

Thank you both, these explanations make me feel a lot better and I understand now!

Hey guys,
The way i interpret the instructions it wants me to use either + or - but neither of those worked.
I managed to solve it, but I’m still not sure why this worked.
Could anyone explain this for me?
Please and Thank You!
-Gio

code:

var array = [1, 12, 21, 2];

// Only change code below this line.

array.sort(function (a, b){
return a < b;
});

Usually we think of the sort() callback as returning a number.

Whenever I am confused about something like this, I just write a test program and start logging stuff out. For example, if I run this code:

var array = [1, 12, 21, 2];

array.sort(function (a, b){
  let comparison = a > b;
  console.log('\n\n***');
  console.log('comparing', a, 'and', b);
  if (comparison)
    console.log('swap');
  else
    console.log('don\'t swap');

  return comparison;
});

console.log('\n\n### final', array);

I get this:


***
comparing 1 and 12
don't swap

***
comparing 12 and 21
don't swap

***
comparing 21 and 2
swap

***
comparing 12 and 2
swap

***
comparing 1 and 2
swap

### final (4) [1, 2, 12, 21] 

When i doubt log it out. When the callback function returns true, that tells sort() that those entries are not in order so need to be swapped.

Let us know if that is not clear.