Sign in
Log inSign up

What I understood about the Array. sort() method in JavaScript!

karthik selvam's photo
karthik selvam
·Sep 19, 2021·

2 min read

What is sort ..?

The sort() method sorts the elements of an array in place and returns the array. This is what we get in MDN docs.

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
//  output:   ["Dec", "Feb", "Jan", "March

The above code really worked as what we expected. But, when it comes to Numbers the situation is Unexpected..!

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
//  output:  [1, 100000, 21, 30, 4]

meme sort.jpg Credit: Reddit

Why ..?

By default Array. sort() method will work for alphabets without a problem. but, when it comes to numbers it causes problems.

let us resolve what is going on

Without argument

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
//  output: Array [1, 100000, 21, 30, 4]

With comparator

const array1 = [1, 30, 4, 21, 100000];
array1.sort((a,b) => a-b) ;
console.log(array1);
//Output: [1, 4, 21, 30, 100000]
const numbers= [1,30,4,21,100000];
numbers.sort(  (a,b) => {

  if (a < b) {
    return -1;
  }
  if (a > b) {
    return 1;
  }
  return 0;
});


//Output: [1, 4, 21, 30, 100000]
  • If (a < b) function returns -1, a will go before b (1 < 30) so, Number 1 is first then 30 is second and it continues the operation until the condition is okay

  • If (a > b) function returns 1, b will go before a (30 > 4) so, Number 4 will go first number 30 will place after a

  • If(a=b) then Nothing will change in order

What if you want descending order ..?

No Problem

const numbers = [1, 30, 4, 21, 100000];

numbers.sort((a,b) => b-a);

console.log(numbers);

// output:  [100000, 30, 21, 4, 1]

Conclusion

Array. sort() method invoked without arguments sorts the elements alphabetically. That’s why using an array. sort() to sort numbers in ascending order doesn’t work.

This is what I understood about Array. sort() method in javascript

External resources

Coding Addict Channel

Dmitri Pavlutin