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 set up custom error pages in .htaccess for your Apache server (ErrorDocument)

What are some ways you can log debug messages and data in JS?

How to sort an array in javascript?

What is the spaceship operator (<=>) in PHP?

What are the SPL Iterators in PHP?

How to add comments in PHP

How to Enable Directory Listings in Apache with .htaccess

What is the difference between empty(), isset(), != null, is_null() in PHP

What is the difference between integration and unit tests?

How to redirect your website to a new domain/location in .htaccess