How To Sort Array In Javascript – Simple Examples

Welcome to a tutorial and examples on how to sort an array in Javascript. Having some trouble trying to sort an array in Javascript? Well, it really isn’t the friendliest in Javascript, but there are ways to do it.

  • Just use THEARRAY.sort(); to sort an array in ascending order.
  • Use THEARRAY.sort().reverse(); to sort an array in descending order.
  • Use THEARRAY.sort(function(a, b){ return a-b; }); to sort an array of numbers in ascending order.
  • Vice-versa, THEARRAY.sort(function(a, b){ return b-a; }); to sort an array of numbers in descending order.

That covers the basic sorting, but read on for more examples!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

REAL QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Array Sort Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

JAVASCRIPT ARRAY SORTING

All right, let us now get into the examples of how to sort an array in Javascript.

 

1) SORT ARRAY IN ASCENDING ORDER

1-sort.html
// (A) NUMERIC + APLHABETIC + ALPHANUMERIC ARRAYS
var arrA = [12, 5, 97, 41];
var arrB = ["John", "Aaron", "Zoe", "June"];
var arrC = ["Ezea888", "123Foo", "Bar456"];

// (B) SORT ARRAY (ASCENDING ORDER)
// 12, 41, 5, 97 - FUNKY!
arrA.sort();
console.log(arrA);

// Aaron, John, June, Zoe - CORRECT
arrB.sort();
console.log(arrB);

// 123Foo, Bar456, Ezea888 - CORRECT
arrC.sort();
console.log(arrC);

A “basic sort” in Javascript is as simple as using ARRAY.sort(), but take extra note of the funky number sorting. Javascript is not wrong, that’s just the way of how it works – All the elements will be converted and compared as strings. So in this case, “4” comes before “5”. Thus the final result of 12, 41, 5, 97.

 

 

2) SORT ARRAY IN DESCENDING ORDER

2-reverse-sort.html
// (A) NUMERIC + APLHABETIC + ALPHANUMERIC ARRAYS
var arrA = [12, 5, 97, 41];
var arrB = ["John", "Aaron", "Zoe", "June"];
var arrC = ["Ezea888", "123Foo", "Bar456"];

// (B) REVERSE SORT ARRAY (DESCENDING ORDER)
// 97, 5, 41, 12 - FUNKY!
arrA.sort().reverse();
console.log(arrA);

// Zoe, June, John, Aaron - CORRECT
arrB.sort().reverse();
console.log(arrB);

// Ezea888, Bar456, 123Foo - CORRECT
arrC.sort().reverse();
console.log(arrC);

Sorting in descending order is not immediately obvious in Javascript. Basically, we do an ascending order sort with sort() first, then use reverse() to reverse the order. Yes, if we just use .reverse() alone, it will simply reverse the order of the elements from last to first.

 

3) SORTING AN ARRAY OF NUMBERS

3-number-sort.html
// (A) NUMERIC + APLHABETIC + ALPHANUMERIC ARRAYS
var arrA = [12, 5, 97, 41];

// (B) FORWARD SORT (ASCENDING)
// 5, 12, 41, 97
var sortasc = function (a, b) { return a - b; }
arrA.sort(sortasc);
console.log(arrA);

// (C) REVERSE SORT (DESCENDING)
// 97, 41, 12, 5
var sortdesc = function (a, b) { return b - a; }
arrA.sort(sortdesc);
console.log(arrA);

// (D) ES6 ARROW FUNCTION "SHORTHAND"
arrA.sort((a,b) => a-b);
arrA.sort((a,b) => b-a);

So how we do sort an array of numbers? As in the introduction, we create our own custom compare functions:

  • To sort numbers in ascending order – function sortASC (a, b) { return a - b; }
  • In descending order – function sortDESC (a, b) { return b - a; }

Then simply pass it in – ARRAY.sort(sortASC). The custom compare function can be rather confusing, so let’s walk through it in the next example.

 

 

4) CUSTOM COMPARE FUNCTION

4-custom-sort.html
// (A) THE ARRAY
var arr = [12, 97, 5, 97, 41];

// (B) SORT WITH CUSTOM COMPARE FUNCTION
arr.sort(function (a, b) {
  // (B1) SORT() WILL LOOP THROUGH EACH ELEMENT OF THE ARRAY
  // "B" IS THE CURRENT ELEMENT
  // "A" IS THE NEXT ELEMENT
  console.log("Current: " + b);
  console.log("Next: " + a);

  // (B2) RETURN RESULT - IF SORTING IN ASCENDING ORDER
  // RETURN 0 IF A==B
  if (a == b) { return 0; }

  // RETURN 1 (OR ANY NUMBER MORE THAN 0) IF A > B
  else if (a > b) { return 1; }

  // RETURN -1 (OR ANY NUMBER LESS THAN 0) IF A < B
  else { return -1; }
});
console.log(arr);

A custom compare function will allow you to specify your own sort algorithm, but it can be pretty confusing at first. A quick explanation:

  • sort() will loop through each element of the array, passing 2 of them into the custom compare function on every round.
  • b is the current element, and a is the next element.
  • The whole idea is to compare a and b, then return a number to specify the sort order. Using an ascending sort order as an example:
    • if (a == b) { return 0; } – Next and current are the same, retain these two side-by-side.
    • if (a > b) { return 1; } – Next is bigger than current. Retain this order, but with respect to other elements; There may be other elements that can sit between these two.
    • if (a < b) { return -1; } – Next is smaller than current. The next element should be placed before this current one.

Yep, kind of hard to grasp at first. Take some time to digest this.

 

 

5) SORTING A NESTED ARRAY

5-nested-sort.html
// (A) NESTED ARRAY
var narr = [
  "Watermelon", "Cherry", 
  ["Foo", "Bar"], "Apple",
  ["Red", "Green", "Blue", ["Magenta", "Cyan"]]
];

// (B) NESTED SORT
function nsort (arr) {
  arr.sort();
  for (let i of arr) {
    if (Array.isArray(i)) { nsort(i); }
  }
}
nsort(narr);
console.log(narr);

Yep, no sweat. To sort a nested array, use a recursive function.

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

INFOGRAPHIC CHEAT SHEET

How To Sort Array In Javascript (click to enlarge)

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *