The best way to use sort in javascript
Tags: javascript, programming, tutorial, algorithms
Published: 2023-08-01 04:30:00

JavaScript is one of the most popular programming languages used by millions of developers over the world. It is used for building Full stack web application using frameworks like [nextjs](https://www.tensorflow.org/js), Mobile applications using frameworks like [react native](https://reactnative.dev/), games development using game engines like [phraser](https://phaser.io/), [melonjs](https://melonjs.org/), data visualization using [d3.js](https://d3js.org/)  and also in the field of machine learning using [ml5.js](https://ml5js.org/), [Tensorflowjs](https://www.tensorflow.org/js), etc.
In this tutorial, you will learn about the `sort()` method in JavaScript resulting in learning how to sort arrays, and objects in JavaScript.

## Syntax and behaviour for `sort()`

```js
function compareFn(x,y){
// some logic which decides the soring order of elements in an array or object 
}
sort(compareFn)
//sorting number arrays
let array = [5,3,2,4,1]
array.sort() // output: [1,2,3,4,5]
//sorting string arrays
const str_arr=['k','p','l','h'];
str_arr.sort()// output:[ 'h', 'k', 'l', 'p' ]
//unexpected behaviour
const array2 = [2,20,21,15,50]
array2.sort()//output: [ 15, 2, 20, 21, 50 ]
```
We you look on the above code block you will find that the `sort()` method is providing desired results for the first two arrays but not for the third example, this is because the `sort()` function in JavaScript first converts the elements into strings and then makes comparison with the first character of each string.
For  arry2 example if we break down into string then we will find that in between "15" and "2" if we compare the first character of each string which is "1" and "2" one comes before  two hence this kind of result. 
In order to solve this problem of sorting number arrays using the `sort()` method we can use the compare function. The compare function looks like the below example
```js
function compareFn(a, b) {
  //if neegative sort a after b
 if (a < b ) {
    return -1;
  }
  ////if positive sort a before b
  if (a > b ) {
    return 1;
  }
  // a and b having same value
  return 0;
}
const array2 = [2,20,21,15,50]
array2.sort(compareFn)//output: [ 2, 15, 20, 21, 50 ]


```
## Sorting arrays in ascending and descending order 
Using the compare function we can define in which order the array to be sorted. The given example shows below
```js

//sorts array in ascending order
function comparisonAscending(a, b) {
    return a - b;
}
const arr = [9, 10, 11, 7];
arr.sort(comparisonAscending)// Output [7,9,10,11]
//sorts array in descending order
function comparisonDecending(a, b) {
    return b - a;
}
arr.sort(comparisonDecending)// Output [11,10,9,7]
```
Let's understand how it works: If we consider the `comparisonAscending` at first it takes [10, 9] in the format [a,b] so a is 10 and b is 9 now if we do (a-b) it is positive so we pick a after b hence 10 comes after 9 in the second pass it takes [11,10] here also (a-b) positive so again 11 is placed after 10 in the third pass [7,11] is compare and (a-b) becomes negative so we pick 7 before 11 same is done in the case of comparison of [7,10] and the again the same in the final pass [7,9] 
 

![Sorting array visualization](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5vv28963uz2bf83lkchi.png)

## Sorting object arrays in JavaScript
To understand how JavaScript objects can be sorted using the `sort()` method let's take an example object shown below.w.

```js
const obj = [{ name: "lola", age: 45, isWorking: true },
{ name: "john", age: 65, isWorking: false },
{ name: "samuel", age: 25, isWorking: true },
 { name: "Kristine", age: 27, isWorking: true },]

```
Object arrays in JavaScript are sorted using the key values inside an object. In the example there are four objects inside the `obj` array, each object has three 3 keys `name`, `age`, and `isWorking`. Using these object keys the objects will be sorted. 
Let's say you want to sort the object using the `name` key in descending order. In that case, we can use the `localeCompare()`. It compares two strings and returns `0`, `1`, and `-1` based on the precedence of the first character of each of the strings.
So you can use the example below example to to sort the object using the `name` key in descending order
```js
obj.sort((a, b) => {
    return b.name.localeCompare(a.name)
})
/* output
 [{"name":"samuel","age":25,"isWorking":true},{"name":"lola","age":45,"isWorking":true},{"name":"Kristine","age":27,"isWorking":true},{"name":"john","age":65,"isWorking":false}] */
```
## Conclusion
I believe the readers of this article will now have a clear understanding of how the Sort method in javascript works.
This article is crafted taking refences from [mdn](https://developer.mozilla.org/en-US/) and [w3Schools](https://www.w3schools.com/).Follow my blog to learn more  javascript topics like a piece of cake. Happy Coding :)