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 change the order that migrations happen?

How to get the first row that matches some where queries, or create it if it doesn't exist (in Laravel's Eloquent)?

How to access the Laravel's route parameters outside of the controller?

How to do comments in Blade files?

How to generate an array for a dropdown (with ['key' => 'value']) suitable for a dropdown, from a Laravel collection of Eloquent objects?

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

How to hide directory listing in .htaccess?

How to Force www or non-www in htaccess

How to merge/concat two arrays together in JS?

What is the null coalescing operator in PHP7?