How to sort an array in javascript?

JavaScript: How to sort an array in javascript?

It is very simple to sort in JS. Just use the .sort() method. But there are a few important things to know and be aware of:

Sorting a-z, just use .sort():

  1.         word_array = [
  2.  
  3.         "animal",
  4.         "phone",
  5.         "water",
  6.         "computer",
  7.         "bottle",
  8.  
  9.         ];
  10.  
  11.         console.log(word_array.sort()); // (5) ["animal", "bottle", "computer", "phone", "water"]

However, if you use .sort() on an array of numbers it will not sort it correctly:

  1.         num_array = [
  2.  
  3.             1000,
  4.             200,
  5.             22,
  6.             2,
  7.             102,
  8.             199,
  9.             150,
  10.             100000,
  11.             2.24,
  12.         ];
  13.  
  14.         console.log(num_array.sort()); //(9) [1000, 100000, 102, 150, 199, 2, 2.24, 200, 22]

The output from this - [1000, 100000, 102, 150, 199, 2, 2.24, 200, 22] is clearly not sorted propperly. It sorted it by comparing character by character, as if it was a string comparison.

You can fix this by providing a comparison function to sort, like this:

  1.         num_array = [
  2.  
  3.             1000,
  4.             200,
  5.             22,
  6.             2,
  7.             102,
  8.             199,
  9.             150,
  10.             100000,
  11.             2.24,
  12.         ];
  13.  
  14.         console.log(num_array.sort(function(a,b) { return a-b; }));

And this will now output the correctly sorted array: [2, 2.24, 22, 102, 150, 199, 200, 1000, 100000]

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about How to sort an array in javascript?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the JavaScript language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to install and use jpegoptim on Linux CentOS

How to use subdomains as parameters in your routes (or in your web.php file)

How to replace whitespace with a single space

How to find out which php.ini file PHP is using?

How to Force www or non-www in htaccess

How to merge/concat two arrays together in JS?

How to check if a (blade) view file exists

What is WordPress default Apache .htaccess rules?

How to create random numbers in JS?

How to check if a user is logged in, inside a blade file?