# Sort Arrays with sort explanation?

**URL:** <https://forum.freecodecamp.org/t/sort-arrays-with-sort-explanation/97077>\
**Category:** General\
**Created:** [March 15, 2017, 8:19pm UTC](https://forum.freecodecamp.org/t/sort-arrays-with-sort-explanation/97077 "2017-03-15T20:19:43Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![DMXGeo](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/dmxgeo/32/39520_2.png) [@DMXGeo](https://forum.freecodecamp.org/u/DMXGeo)\
**Post date:** [March 15, 2017, 8:19pm UTC](https://forum.freecodecamp.org/t/sort-arrays-with-sort-explanation/97077/1 "2017-03-15T20:19:43Z")

</div>

```auto
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.

---

<div class="post-metadata">

**Author:** ![ryanjgross](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/ryanjgross/32/100550_2.png) [@ryanjgross](https://forum.freecodecamp.org/u/ryanjgross)\
**Post date:** [March 15, 2017, 8:34pm UTC](https://forum.freecodecamp.org/t/sort-arrays-with-sort-explanation/97077/2 "2017-03-15T20:34:14Z")

</div>

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.

```auto
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:

```auto
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.

> **[Array.prototype.sort()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)**
>
> The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.

  
[https://www.w3schools.com/jsref/jsref\_sort.asp](https://www.w3schools.com/jsref/jsref_sort.asp)

---

<div class="post-metadata">

**Author:** ![kevinSmith](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/kevinsmith/32/72934_2.png) [@kevinSmith](https://forum.freecodecamp.org/u/kevinSmith)\
**Post date:** [March 15, 2017, 8:52pm UTC](https://forum.freecodecamp.org/t/sort-arrays-with-sort-explanation/97077/3 "2017-03-15T20:52:45Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![DMXGeo](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/dmxgeo/32/39520_2.png) [@DMXGeo](https://forum.freecodecamp.org/u/DMXGeo)\
**Post date:** [March 16, 2017, 4:57am UTC](https://forum.freecodecamp.org/t/sort-arrays-with-sort-explanation/97077/4 "2017-03-16T04:57:01Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![RPGi0](https://avatars.discourse-cdn.com/v4/letter/r/c67d28/32.png) [@RPGi0](https://forum.freecodecamp.org/u/RPGi0)\
**Post date:** [November 14, 2017, 8:19pm UTC](https://forum.freecodecamp.org/t/sort-arrays-with-sort-explanation/97077/5 "2017-11-14T20:19:13Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![kevinSmith](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/kevinsmith/32/72934_2.png) [@kevinSmith](https://forum.freecodecamp.org/u/kevinSmith)\
**Post date:** [November 14, 2017, 9:26pm UTC](https://forum.freecodecamp.org/t/sort-arrays-with-sort-explanation/97077/6 "2017-11-14T21:26:25Z")

</div>

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:

```auto
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:

```auto

***
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.

---

<div class="post-metadata">

**Author:** ![ILM](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/ilm/32/363239_2.png) [@ILM](https://forum.freecodecamp.org/u/ILM)\
**Post date:** [January 16, 2021, 5:25pm UTC](https://forum.freecodecamp.org/t/sort-arrays-with-sort-explanation/97077/7 "2021-01-16T17:25:26Z")

</div>

Closed on January 16, 2021, 5:25pm UTC


