DEV Community

Cover image for The best way to use sort in javascript
Kumar Kalyan
Kumar Kalyan

Posted on • Updated on

The best way to use sort in javascript

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, Mobile applications using frameworks like react native, games development using game engines like phraser, melonjs, data visualization using d3.js and also in the field of machine learning using ml5.js, Tensorflowjs, 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()

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 ]
Enter fullscreen mode Exit fullscreen mode

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

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 ]


Enter fullscreen mode Exit fullscreen mode

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


//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]
Enter fullscreen mode Exit fullscreen mode

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

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.

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 },]

Enter fullscreen mode Exit fullscreen mode

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

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}] */
Enter fullscreen mode Exit fullscreen mode

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 and w3Schools.Follow my blog to learn more javascript topics like a piece of cake. Happy Coding :)

Top comments (0)