Different ways to sort array in JavaScript

Free Linux Book

Get FREE domain for 1st year and build your brand new site

In this article, we have explained Different ways to sort array in JavaScript which includes sort() method, localeCompare(), orderBy() and much more.

Table Contents

1. Introduction

2. sort() Method

2.1. Alphabetical order

2.2. Ascending order

2.3. Descending order

2.4. Reverse order

3. localeCompare() Method

4. parseInt() Function

5. Lodash _.orderBy() Method

6. Lodash _.sortBy() Method

7. Intl

7.1. Intl.Collator()

7.2. Intl.DateTimeFormat()

7.3. Intl.NumberFormat()

8. Final Considerations

Reference


1. Introduction


There are several ways to sort data into arrays to get the necessary information. In the article, we'll describe some cases where the array stores integers, strings, or custom objects.

2. sort() Method


The sort method rearranges the elements within the array and can sort strings and numbers ascending and descending.

2.1. Alphabetical order


By default, sort() method sorts strings alphabetically and numbers in ascending order.
In the example in Figure 1, the words are sorted alphabetically, returning as a result: ['C', 'JavaScript', 'Kotlin', 'Python'].

var lang1 = ["JavaScript", "Kotlin", "Python", "C"];
console.log(lang1.sort());

Figure 1. Sort() method to sort the words alphabetically.

2.2. Ascending order


In the case of numbers, the numeric matrix converts to a string. The order of the number will not be given by its value but by its writing (alphabetical order).
To use the sort() method, a comparison function is needed. This function will compare two values and then sort them according to the generated value.

  • if the result is negative, a is classified before b;
  • if the result is positive, b is classified before a;
  • if the result is zero, nothing changes.
    In the example code in Figure 2, the numeric array [99, 87, 3] returns after its sorting in ascending order the result [3, 87, 99]
const number = [99, 87, 3];

console.log(number.sort(function(a, b){return a - b})); 

Figure 2. Sort() method in a numeric array (ascending order).

2.4. Descending order


For descending order, the same ascending order assumption was used. However, this time, the a parameter will subtract the b parameter.
In Figure 3, the numeric array was sorted in descending order generating [93, 74, 5, 2]

const number = [5, 2, 93, 74];

console.log(number.sort(function(a, b){return b - a})); 

Figure 3. Numeric array arranged in descending order.

2.5. Reverse order


To reverse the order of an array composed of strings:

  • first, order the elements of the array with the sort() command;
  • after reversing the order with the reverse() command.

In the example in Figure 4, the list of words was arranged in reverse alphabetical order generating ['Turmaline', 'Sodalite', 'Quartz', 'Feldspat'].

var mineral = ["Turmaline", "Quartz", "Feldspat", "Sodalite"]
mineral.sort();
console.log(mineral.reverse());

Figure 4. The sorting array of strings in descending order

3. localeCompare() Method


The localeCompare() method returns a numeric value indicating the location of the string (comes before, after, or is the same as the given string in sort order).

  • value equal to -1, if it comes before;
  • value equal to 1, if it comes later;
  • value equal to 0, nothing changes.

In Figure 5, the comparison of the location of the string abcd with fghi was performed. As a result, the value 1 was obtained, indicating that abcd is in a position before fghi.

let txt1 = "fghi";
let txt2 = "abcd";
console.log(txt1.localeCompare(txt2));

Figure 5. Localization of the string with the localeCompare() method.

4. parseInt() Function


This function parses the string argument and returns an integer in the specified base.
A base has a value between 2 and 36. It is always necessary to specify this parameter to avoid confusion.

If the first character cannot be converted to a number, the code will return NaN.
In Figure 6, an array composed of strings ['10', '32', '43'] with base 10 was provided, which with the parseInt function were converted into a numeric array [10 , 32, 43].

var l = ['10','32','43']
var res = l.map(function (x) { 
  return parseInt(x, 10); 
});

console.log(res);

Figure 6. Transforming string to integer with parseInt().

5. Lodash _.orderBy() Method


Lodash is a JavaScript library that helps handle arrays, strings, collections, objects, numbers, etc.

_.orderBy() allows sorting of iteration orders into "asc" (ascending) and "desc" (descending).
In addition, three parameters are accepted:

  • collection, contains the collection to iterate over;
  • iteratee, contains the iteratees to sort by;
  • order, contains the rank orders of the iteratories.

In Figure 7, the info were sorted in ascending order, and the numeric values in descending order.

const _ = require("lodash"); 

var test = [
  { 'info': 'A',   'value': 90 },
  { 'info': 'B', 'value': 38 },
  { 'info': 'A',   'value': 41 },
  { 'info': 'B', 'value': 32 }
];
     
let res = _.orderBy(test, ['test', 
           'value'], ['asc', 'desc']);

console.log(res);

Figure 7. Lodash _.orderBy() Method for ascending and descending ordering of the array.

The result (Figure 8) obtained from the code in Figure 7:

[
{ info: 'A', value: 90 },
{ info: 'A', value: 41 },
{ info: 'B', value: 38 },
{ info: 'B', value: 32 }
]

Figure 8. Result generated with Lodash _.orderBy() in Figure 7.

6. Lodash _.sortBy() Method


_.sortBy() is similar to _.orderBy(), both use the Lodash library. However, this method generates an array of elements sorted in ascending order (interaction between collection and iterator). The classification generated in this method is stable, showing the original classification order of the same elements. Unlike _.orderBy(), _.sortBy() accepts two parameters: - collection, collection to iterate; - iteratees, contain the iteratees to sort and an argument (value).

In the example in Figure 9, the values are sorted in ascending order with _.sortBy():

const _ = require("lodash"); 
       
var object = [
  { 'obj': 'K', 'value': 9 },
  { 'obj': 'Y', 'value': 8 },
  { 'obj': 'K', 'value': 7 },
  { 'obj': 'Y', 'value': 5 } ];
   
let res = _.sortBy(object, ['obj', 'value']);
  
console.log(res);

const _ = require("lodash"); 
       
var object = [
  { 'obj': 'K', 'value': 9 },
  { 'obj': 'Y', 'value': 8 },
  { 'obj': 'K', 'value': 7 },
  { 'obj': 'Y', 'value': 5 } ];
   
let res = _.sortBy(object, ['obj', 'value']);
  
console.log(res);

Figure 9.Lodash _.sortBy() method for ascending ordering of array.

The result (Figure 10) generated in the code (Figure 9) above:

[
{ obj: 'K', value: 7 },
{ obj: 'K', value: 9 },
{ obj: 'Y', value: 5 },
{ obj: 'Y', value: 8 }
]

Figure 10. Result generated with Lodash _.sortBy() in the code (Figure 9).

7. Intl


Intl is an object that provides language-sensitive and formatting (numbers, date, and time) string comparison. They are used with Collator, NumberFormat and DateTimeFormat constructors.

7.1. Intl.Collator()


The collator() constructor allows for language-sensitive string comparison.
In the example in Figure 11, using collator() allowed you to sort strings that contain characters other than the Roman alphabet. As a result we obtained ['a', 'รค', 'z', 'Z'].

console.log(['Z', 'a', 'z', 'รค'].sort(new Intl.Collator('de').compare));

Figure 11. Sorting the array with collator().

7.2. Intl.DateTimeFormat()


The builder allows language-sensitive date and time formatting. In the example in Figure 12, we defined the day, month, and year format that the code should generate.
const date = new Date(Date.UTC(2021, 22, 17, 3, 23, 16, 738));
console.log(new Intl.DateTimeFormat('en-GB', { dateStyle: 'full', timeStyle: 'long' }).format(date));

Figure 12. Intl.DateTimeFormat() constructor for date formatting.

The result (Figure 13) obtained in the code in Figure 12 was:

Thursday, 17 November 2022 at 12:23:16 GMT+9

Figure 13. Result obtained in the code of Figure 12.

7.3. Intl.NumberFormat()


The numberFormat() is an object constructor that allows language-sensitive number formatting.
In Figure 14, a number has been transformed into a yen (Japanese money) format resulting in * ๏ฟฅ 543,790 *.

const number = 543789.7897;
console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number));

Figure 14. Builder for sensitive number formatting.

8. Final Considerations


The ordering and formatting of the array allow you to identify the information contained within the arrays.

In this article at OpenGenus, we showed some ways to work with the content of arrays, but there are other ways.