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

What are the SPL Iterators in PHP?

What are route patterns in Laravel?

What are Template literals (Template strings) in JS?

How to namespace a Laravel route group?

What is the max size, by default, of GET variables?

Is multiple inheritance supported in PHP?

How to fix the MySQL related "Specified key was too long error" error in Laravel

How to show a specific view file for certain error codes?

How to get the last character of a string in JS?

How to set up custom error pages in .htaccess for your Apache server (ErrorDocument)