DEV Community

Cover image for Javascript Sort: Simplified🧑‍💻
Gautam Anand
Gautam Anand

Posted on • Edited on

Javascript Sort: Simplified🧑‍💻

Is Javascript Sorting Simple?

Let's just admit that we all have gone to StackOverflow and just copied and pasted the javascript sort() method.

Well, I hope after reading this article, you might stop doing it and start writing your own custom javascript sorting methods.

Basics

  • To begin with any function, we need to understand the very basics of the sort() method.

  • It is a Higher Order Function, we'll know how.

  • As the name suggests, it sorts the elements in the array.

How?

Working of sort()

I love explaining with examples.

const array = ["Harry", "John", "Bob", "Zayn", "Chris"];
console.log(array.sort()); // [ 'Bob', 'Chris', 'Harry', 'John', 'Zayn' ]
Enter fullscreen mode Exit fullscreen mode

This works exactly like sort(), except that it works only like this when we are sorting strings.

This is the default behavior of Javascript Sort() function - It converts the elements to string and compares the INSIDE value(i.e. the UTF-8 values) and returns the sorted array

For UTF-8 reference check this cheatsheet!
Alternatively, you may try running the below script

console.log("a".charCodeAt(0)); // 97
Enter fullscreen mode Exit fullscreen mode

So in the above example, it resulted us the correct output because it actually looked up the UTF-8 values of the elements.

Suppose we have the same array variable

array.forEach((element) =>
  console.log(element.charCodeAt(0), " ", element.charAt(0))
);
Enter fullscreen mode Exit fullscreen mode

This would actually tell us what is the value that was compared in real like this.

// console output
66   B
67   C
72   H
74   J
90   Z
Enter fullscreen mode Exit fullscreen mode

Hence, Now when we actually try to sort an array full of numbers using the sort() function, we don't get the EXPECTED result.

Example

const array = [54, 133, 96, 0, 31, 101];
console.log(array.sort());
Enter fullscreen mode Exit fullscreen mode

This will result an array like this - [0, 101, 133, 31, 54, 96] and the reason is stated above.

Solution

If you were reading up to here carefully, you must've remembered that sort is a higher-order function.
which basically means that it takes a callback() function as an argument.

  • The callback function takes two arguments(a,b)
  • a is the first element of the array and b is the second element.
  • It should return any of the three values: (-1, 0, 1) according to our requirements.
if negative: a < b
if positive: a > b
if zero: a == b // let it be as it is.
Enter fullscreen mode Exit fullscreen mode

Writing our first compare function

It would be as simple as writing basic if else.

function compareFn(a, b) {
  if (a < b) return -1;
  else if (a > b) return 1;
  else return 0;
}
Enter fullscreen mode Exit fullscreen mode

Let's just put our compareFn() in action!

const numbers = [54, 133, 31, 96, 0, 31, 101, 101];

function compareFn(a, b) {
  if (a < b) return -1; //BOOKMARK
  else if (a > b) return 1;
  else return 0; // means its equal
}

console.log(numbers.sort(compareFn)); // [ 0,  31,  31,  54, 96, 101, 101, 133 ]
Enter fullscreen mode Exit fullscreen mode

See? we did it!
We actually sorted an array with numerical values!

But wait do we have to write the whole above logic just to create a sort() function that sorts numbers?
Javascript cannot be this harsh to us right?

It's not.

Our Final Touch to sort() function.

Well if we look closely to this line in our compare function

if (a < b) return -1;
Enter fullscreen mode Exit fullscreen mode

NOTE:

This condition can only occur when we try to subtract a larger number from a smaller number that would result in a negative number.

Read that again!

So if we subtract b from a, this actually solves our all of the problems.

Listen.
We wanted a negative, a positive, and a zero right?

const a = 10;
const b = 100;
console.log(a - b); // would be negative
Enter fullscreen mode Exit fullscreen mode

Also,

const a = 100;
const b = 10;
console.log(a - b); // would be positive
Enter fullscreen mode Exit fullscreen mode

And if they are equal then it would actually give us zero.

This actually will sort our array again in an ASCENDING order with a much cleaner code.

We just cracked it!

Instead of writing the whole logic, we could just write our compare function like this.

function compareFn(a, b) {
  return a - b; // does all the job...
}
Enter fullscreen mode Exit fullscreen mode

Now when we look at the code it should look like this

const numbers = [54, 133, 31, 96, 0, 31, 101, 101];

function compareFn(a, b) {
  return a - b; // b - a for descending order for obvious reasons.
}
console.log(numbers.sort(compareFn)); // [ 0,  31,  31,  54, 96, 101, 101, 133 ]
Enter fullscreen mode Exit fullscreen mode

And since we know it just has a single line we can use an arrow function instead.

const nums = [6, 3, 8, 2, 5, 1];
console.log(nums.sort((a, b) => a - b)); // [1,2,3,5,6,8]
Enter fullscreen mode Exit fullscreen mode

That's it.
Thank you for reading up to here,
If you really find this useful, share this blog with your friends, your co-workers, or anyone in your family who loves or hates javascript!

Social Links 👇
🌐Website
💻LinkedIn
🎶Instagram

Top comments (6)

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

Ok, so this is not really "writing your own sort()". This is merely providing an appropriate comparer function.

Collapse
 
localhostd3veloper profile image
Gautam Anand

I’d just focus on the very basics, if you know the basics you can actually write your own compartor function

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

I understand. It would still not be "write your own sort()". It would be "write your own comparer".

Thread Thread
 
localhostd3veloper profile image
Gautam Anand

Understood

Collapse
 
localhostd3veloper profile image
Gautam Anand

I get this feeling everyday ❤️🤌🏼