Tutorials Tonight's Logo

JAVASCRIPT SORT ARRAY


JavaScript provides sort() method which allows us to sort an array of numbers, string and objects.

In this tutorial, you will understand how to sort() method works and how to use it to sort array and object on the basis of various different parameters.

sort array in javascript

sort method in JavaScript

Let's see how does sort function work in JavaScript.

The sort() method sorts an array alphabetically and returns the array. The default sort order is ascending.

Example of sorting a string array.

let lang = ["HTML", "CSS", "Javascript", "SQL", "Python"];
lang.sort();
console.log(lang);
▶ Try It

The sort() method converts elements into string and then compare there sequence of UTF-16 code units values to sort them.

Because of the above fact if you apply the sort method directly on an array of numbers it does not get sorted by the number value.

let num = [61, 8, 20, 5, 1, 11, 9, 3];
num.sort();
console.log(num);
▶ Try It

In the output of above example the sort() method places 20 before 3 and 61 before 8 because the numbers get converted to string and "20" comes before "3" when compare their UTF-16 code units values.

Then what should you do to sort the array elements in increasing order by number value?

To fix this you need to pass a compare function in sort method.

The sort() method accepts a function as an optional argument. This function determines the order of sorting the elements.

The following is the syntax of sort() method with compare function.

array.sort(compareFunction);

Note: If compare function is not supplied then all valid array elements are sorted by converting them to strings and comparing strings in UTF-16 code units.

Compare function

The compare function in the sort method accepts 2 arguments generally called a and b.

a and b are 2 numbers of the array that are being compared at any moment of the function execution. The compare function sorts the element on the basis of the return value of compare function.

function compareFunction(a, b) {
  // ...
}

If these numbers are being compared then:

  1. If compareFunction(a, b) returns less than 0, then sort() method sorts a at lower index than b. Simply a will come before b.
  2. If compareFunction(a, b) returns equal to 0, then sort() method leave the element positions as it is.
  3. If compareFunction(a, b) returns greater than 0, then sort() method sorts a at greater index than b. Simply a will come after b.



javascript sort array of numbers

Let's use the concept of compare function and sort an array of numbers.

let arr = [61, 8, 20, 5, 1, 11, 9, 3];
function compareFunction(a, b) {
  if (a > b) return 1;
  if (a = b) return 0;
  if (a < b) return -1;
  // or simply return -1
}
arr.sort(compareFunction);
console.log(arr);
▶ Try It

If array elements are numbers and are not Infinity then instead of returning on the base of 3 conditions as in above example simply return a - b which will be equivalent to above 3 conditions.

let arr = [61, 8, 20, 5, 1, 11, 9, 3];
function compareFunction(a, b) {
  return a - b;
}
arr.sort(compareFunction);
console.log(arr);
▶ Try It

Example explained:

Let's check for first 3 elements of the array. i.e [61, 8, 20]

compareFunction(61 ,8); // return 53, a > b
compareFunction(61 ,20); // return 41, a > b
compareFunction(8 ,20); // return -12, a < b

You can also define function expression within sort method.

let arr = [61, 8, 20, 5, 1, 11, 9, 3];
arr.sort(function (a, b) {
  return a - b;
});
console.log(arr);
▶ Try It

Or you can define compare function using an arrow function.

let arr = [61, 8, 20, 5, 1, 11, 9, 3];
const compareFunction = (a, b) => (a - b);
arr.sort(compareFunction);
console.log(arr);
▶ Try It

Or simply you can write. (arrow function as function expression)

let arr = [61, 8, 20, 5, 1, 11, 9, 3];
arr.sort((a, b) => (a - b));
console.log(arr);

Sort array of string

Sorting string of array is very simple using JavaScript, just apply sort() method on the array of string and by default, it will sort an array of a string in ascending order.

let lang = ["HTML", "CSS", "Javascript", "SQL", "Python"];
lang.sort();
console.log(lang);
▶ Try It

But how will you sort the array in descending order?

To compare string in reverse order use compare function. You need to change the logic of compare function and pass it to sort method as shown in the code below.

let lang = ["HTML", "CSS", "Javascript", "SQL", "Python"];
function compare(a, b) {
  if (a > b) return -1;
  if (a < b) return 1;
  return 0;
}
lang.sort(compare);
console.log(lang);
▶ Try It

Or simply use the reverse method on the array.

let lang = ["HTML", "CSS", "Javascript", "SQL", "Python"];
lang.reverse();
console.log(lang);

Sorting non-ASCII characters

To sort string with non-ASCII characters, i.e. String from other language é, è, a, ä, etc. Use String.localeCompare.

This function can compare non-ASCII characters so they appear in the right order.

let employee = ["zèbree", "communiqué", "éclair", "réservé", "écureuill"]
function compare(a, b) {
  return a.localeCompare(b)
}
employee.sort(compare);
console.log(employee);
▶ Try It

Javascript sort array of objects

To sort an array of object you can not directly use sort() method. You will have to use compare function to decide the order of object depending on different property values.

Use compare function and return on the basis of the property. example a.age - b.age see in the code below.

let employee = [
  { name: "John", age: 35, joined: "Wed Feb 03 2011" },
  { name: "Mike", age: 28, joined: "Mon Feb 05 2001" },
  { name: "Herry", age: 32, joined: "Tue May 22 2012" },
  { name: "Sara", age: 24, joined: "Wed Aug 15 2018" },
  { name: "David", age: 33, joined: "Mon Oct 27 2008" }
]
function compare(a, b) {
  return a.age > b.age;
}
employee.sort(compare);
console.log(employee);
// use console.table for better output look
▶ Try It

Output using console.table

sort array of objects 1

javascript sort array of objects by property (joining date)

Let's sort the object on the basis of joining date property.

Since 'joining' in the object is string value, first convert the value of joining string value to a date object and then use this in compare function to return value.

let employee = [
  { name: "John", age: 35, joined: "Wed Feb 03 2011" },
  { name: "Mike", age: 28, joined: "Mon Feb 05 2001" },
  { name: "Herry", age: 32, joined: "Tue May 22 2012" },
  { name: "Sara", age: 24, joined: "Wed Aug 15 2018" },
  { name: "David", age: 33, joined: "Mon Oct 27 2008" }
]
function compare(a, b) {
  return new Date(a.joined) > new Date(b.joined);
}
employee.sort(compare);
console.log(employee);
// use console.table for better output look
▶ Try It

Output using console.table

sort array of objects 2

Sorting objects by string property

To sort the employees array by their name convert employee name to lowercase and pass it in compare function.

let employee = [
  { name: "John", age: 35, joined: "Wed Feb 03 2011" },
  { name: "Mike", age: 28, joined: "Mon Feb 05 2001" },
  { name: "Herry", age: 32, joined: "Tue May 22 2012" },
  { name: "Sara", age: 24, joined: "Wed Aug 15 2018" },
  { name: "David", age: 33, joined: "Mon Oct 27 2008" }
]
function compare(a, b) {
  let nameA = a.name, nameB = b.name;
  if (nameA > nameB) return 1;
  if (nameA < nameB) return -1;
  return 0;
}
employee.sort(compare);
console.log(employee);
▶ Try It

Conclusion: In this tutorial, we learn how to sort an array of numbers, strings and objects using built-in sort() method.


Follow Us

Copyright © Tutorials Tonight. All Rights Are Reserved.