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 find the 2nd most common item in an array?

An overview of every main PHP array function

How to eager load multiple levels of relationships in Eloquent?

What is the null coalescing operator in PHP7?

How to find the intersection (same values) from two arrays?

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

How to add the CSRF (Cross-site request forgery) token in Laravel?

How to block access to certain referrers in Apache using .htaccess

How to enable the rewrite engine in .htaccess?

How do you run a PHP script from the command line?