Array.prototype.sort() method tutorial
Tags: beginners, javascript, tutorial
Published: 2021-10-16 21:10:09

#The "Array.prototype.sort()" method sorts elements by comparing one element to the next, and returns the same array sorted. 
&nbsp;
##Warning! This method is destructive!
&nbsp;
Lets start with an array of names.
&nbsp;
```
let names = ["Sam", "Dean", "Castiel", "Charlie", "Bobby"]
console.log(names)
// expected output ["Sam", "Dean", "Castiel", "Charlie", "Bobby"]

names.sort()
console.log(names)
//['Bobby', 'Castiel', 'Charlie', 'Dean', 'Sam']

```
Congratulations! You just sorted your first array. As you can see by default the sort method uses the first character of each method in the array and sorts them in ascending order. Did you notice something weird though? The array was mutated. The names list that you made is different now.
&nbsp;
Let's try to stop the array from being mutated by making it a new Array.
&nbsp;
```
let names = ["Sam", "Dean", "Castiel", "Charlie", "Bobby"]
console.log(names)
// expected output ["Sam", "Dean", "Castiel", "Charlie", "Bobby"]

let namesSorted = new Array(names.sort())
console.log(names)
//[['Bobby', 'Castiel', 'Charlie', 'Dean', 'Sam']]

console.log(namesSorted)
//[['Bobby', 'Castiel', 'Charlie', 'Dean', 'Sam']]
```

#####_Even though we tried to prevent names from being mutated by declaring a new variable the original array is still destroyed._


&nbsp;
As you can see because of how the sort() method works, the intial array was mutated and sorted in place. This makes the sort() method a destructive method. You will be unable to access the original array after calling the method.
&nbsp; 
The sort() method not only works to re-order alphabetically but also to organize numbers. Using an empty sort() method will cause numbers to be sorted numerically based on their first character which is why you see 100 being placed numerically in front of 3.
&nbsp; 

```
let characterDeaths = [ 8 ,100, 6, 3, 4]
console.log(characterDeaths.sort())

//[100,3,4,6,8]
```

&nbsp;

To drive the point home we'll use these numbers. You'll see that when 2 characters are compared and match. The program then compares the next character and so on to determine the order.

&nbsp; 

```
let numbersExaggerated = [ 24005,242,2222,9870,199999999]
console.log(numbersExaggerated.sort())

//[199999999, 2222, 24005, 242, 9870] 
```
&nbsp; 
Although this might surprise and frustrate you to no end, the program is working exactly as it has been told.
&nbsp;
In order to compare values the sort() method  must be passed a compareFunction that will tell it how to compare objects in an array. This can be accomplished through various syntax which can be chosen by you based on which you think is easiest to read in your code base.

&nbsp;
The standard compare function will subtract one number from the next and work to help the sort method place numbers in ascending order (if the array doesn't contain NaN or Infinity) it is written as such.

`let compareFunction = function(a,b) {
    let total = a-b 
 return total
}`

```
let characterDeaths = [ 8 ,100, 6, 3, 4]

let compareFunction = function(a,b) {
    let total = a-b 
 return total
}

console.log(characterDeaths.sort(compareFunction))
//[3,4,6,8,100] 

console.log(characterDeaths.sort(function(a,b) {
    return a-b
}))
//[3,4,6,8,100]

console.log(characterDeaths.sort((a,b)=>a - b))
//[3,4,6,8,100]

```

&nbsp; 
Another use for the sort method is sorting arrays of  objects based on the values of one of their properties. 
&nbsp; 
```
let characters = [
    {name:'Sam', deaths:8},
    {name:'Dean', deaths:100},
    {name:'Castiel', deaths:6},
    {name:'Charlie', deaths:3},
    {name:'Bobby' , deaths:4}
]

console.log(characters.sort((a,b)=>a.deaths-b.deaths))

//expected output 
// [
//   { name: 'Charlie', deaths: 3 },
//   { name: 'Bobby', deaths: 4 },
//   { name: 'Castiel', deaths: 6 },
//   { name: 'Sam', deaths: 8 },
//   { name: 'Dean', deaths: 100 }
// ]
```
&nbsp; 
To sort objects by name you can use the String.localeCompare() method in place of the standard compareFunction (a,b) => a-b.
&nbsp; 

```
let characters = [
    {name:'Sam', deaths:8},
    {name:'Dean', deaths:100},
    {name:'Castiel', deaths:6},
    {name:'Charlie', deaths:3},
    {name:'Bobby' , deaths:4}
]

console.log(characters.sort(function(a,b) {
   let nameA = a.name.toLowerCase()  // <---ignores case
    let nameB = b.name.toLowerCase()
    return nameA.localeCompare(nameB)}))


// expected output 
// [
//  { name: 'Bobby', deaths: 4 },
//  { name: 'Castiel', deaths: 6 },
//  { name: 'Charlie', deaths: 3 },
//  { name: 'Dean', deaths: 100 },
//  { name: 'Sam', deaths: 8 }
// ]
```

&nbsp; 
To compare strings with accented characters (non-ASCII) ie. strings from languages other than English. You can use the same function.
&nbsp; 

```

let nonAsciiChar =[ 'é', "be", 'a', 'd', 'e']

console.log(nonAsciiChar)

nonAsciiChar.sort(function (a,b) {
    return a.localeCompare(b)
})

console.log(nonAsciiChar)
```
&nbsp;

Let's create a function that would allow us to save time sorting in the future. We can build a straight-forward framework using the lesser than or greater than approach that will allow us to increment position in the array by 1 position. This is as close to a macro lens as I can think of to explain the sort function.

&nbsp; 
The function will use any property name that is shared by the objects in the array. Since object property names default to strings, when we call the function we will need to input a string that is the property name in place of (prop).

&nbsp; 

TLDR; this function sorts using the value on any property name given.

```
let characters = [
    {name:'Sam', deaths:8},
    {name:'Dean', deaths:100},
    {name:'Castiel', deaths:6},
    {name:'Charlie', deaths:3},
    {name:'Bobby' , deaths:4}
]

let customSort = function (prop){
return characters.sort((a,b)=> {
if( a[prop] > b[prop]){ 
return 1
}
if( a[prop] < b[prop]){
return -1
}
else{
return 0 
} } ) 

}

console.log(customSort("deaths"))
//expected output
[
  { name: 'Charlie', deaths: 3 },
  { name: 'Bobby', deaths: 4 },
  { name: 'Castiel', deaths: 6 },
  { name: 'Sam', deaths: 8 },
  { name: 'Dean', deaths: 100 }
]
console.log(customSort("name"))

[
  { name: 'Bobby', deaths: 4 },
  { name: 'Castiel', deaths: 6 },
  { name: 'Charlie', deaths: 3 },
  { name: 'Dean', deaths: 100 },
  { name: 'Sam', deaths: 8 }
]

```


&nbsp; 
In the event you're sorting large data sets. It may be useful to combine the sort() method with the map() method, if your program is bottle-necked around the sort method. Go to [mapSort](https://github.com/Pimm/mapsort) if you want to learn more about this useful combination.