javascript array sort - javascript array sorting - javascript sorting arrays

Javascript Array Sort — Moving The Links Around

Javascript arrays are a special kind of variable which can hold more than one value at a time, especially useful for processing one after another. This blog post will cover the how to sort Javascript arrays in a variety of ways, with a variety of value types.

One “loops through” each value by using an index value, beginning with 0. Following is a Javascript array of lottery numbers:

let winners = [ 32, 23, 5, 11, 17, 21 ] ;
console.log( winners[0] ) ;

32

The Javascript sort() method rearranges the elements of an array in either an ascending (up) or descending (down) order. By default, sort() compares the values as strings and processes them in ascending order. Additional work — described below — is required for descending order and numeric values.

Unexpectedly, console.log(winners.sort()) returns:

[ 11, 17, 21, 23, 32, 5 ]

Unexpected, because 5 is obviously out of order. Because the default way of looking at the array values is as strings, the sort order makes perfect sense because the string “5” is alphabetically after “11” but makes no sense when viewing the list as numbers.  

Javascript Numeric Array Sorting

Sorting a Javascript array as numbers requires a comparison function to specify an alternative sort order. This function compares two parameters and a number denoting the relationship between the parameters; a zero, a positive value, or a negative value. The general form of a numeric comparison function is as follows:

winners.sort( function( a , b ){
    if( a > b ) return 1 ; // b is sorted before a
    if( a < b ) return -1 ; // a is sorted before b
    return 0 ; // no change needed
}) ;

Using Javascript’s conditional (ternary) operator we can write this more tightly:

winners.sort( function( a , b ){ return a == b ? 0 : a > b ? 1 : -1 ; } ) ;

Now console.log( winners ) returns the expected numeric sort order:

[ 5, 11, 17, 21, 23, 32 ]

Math.min() and Math.max() Are Faster Then Sorting

Numerically sorting our Javascript array results in the minimum value being at winners[0] and the maximum at winners[winners.length], but sorting an array — especially a large array — just to find these values is woefully inefficient. Instead, using the Javascript Math.min() and Math.max() functions is faster and it’s more obvious in reading the code exactly what’s desired:

console.log( Math.min.apply( null, winners ), Math.max.apply( null, winners ) ) ;

5 32

Putting a Javascript Array Into Random Order

To put a Javascript array into a reasonably random order we ignore the usual sort parameters and simply return a value constructed with Math.random():

console.log( winners.sort( function( a , b ){ return 0.5 - Math.random() } ));

Javascript Alphabetic Array Sorting

Consider the following Javascript array containing names:

const people = [ "Ólafur Arnalds", "Eve Kosofsky", "Abbey Lee", "Gena Rowlands", "Pina Bausch", "Hart Bochner" ] ;

As mentioned above, the default Javascript sorting algorithm assumes the array contains ASCII character string values; console.log( people.sort() ) returns:

[ "Abbey Lee", "Eve Kosofsky", "Gena Rowlands", "Hart Bochner", "Pina Bausch", "Ólafur Arnalds" ]

Note that the last name returned begins with an accented letter, and so the list of names doesn’t appear as most would intuitively sort them (with ‘o’ before ‘p’). Just as was required of numeric sorting, we need a special Javascript array sort comparison function.

In this case, the localeCompare() method — which compares two strings in the current locale (derived from  the language settings of the browser — comes to the rescue. Used in the following example, in place of the return a == b ? 0 : a > b ? 1 : -1 code that was used above, this bit of code works worldwide:

console.log( people.sort(function (x, y) {
    let a = x.toUpperCase(), b = y.toUpperCase();
    return a.localeCompare(b);
}));

The output shows the names sorted in “natural” order:

[ "Abbey Lee", "Eve Kosofsky", "Gena Rowlands", "Hart Bochner", "Ólafur Arnalds", "Pina Bausch" ]

More Javascript Array Sorting

reverse()

The code console.log( people.reverse() ) shows how to reverse the existing elements in an array:

[ “Pina Bausch”, “Ólafur Arnalds”, “Hart Bochner”, “Gena Rowlands”, “Eve Kosofsky”, “Abbey Lee” ]

Sorting Javascript Array Objects

Sorting Javascript array objects requires only a simple tweak to specify the characteristic on which to sort. For example, consider the following array of people objects which now contain a birth year:

let people = [ 
  { name: "Ólafur Arnalds", birth: 1986 },
  { name: "Eve Kosofsky", birth: 1950 },
  { name: "Abbey Lee", birth: 1987 },
  { name: "Gena Rowlands", birth: 1930 },
  { name: "Pina Bausch", birth: 1940 },
  { name: "Hart Bochner", birth: 1956 }
] ;

Modify the comparison function to sort by the birth year. Note the use of the console.table() function to output tabular data.

console.table( people.sort(function (x, y) { return x.birth - y.birth ; }));

The output shows the people sorted by birth day:

(index)namebirth
0Gena Rowlands1930
1Pina Bausch1940
2Eve Kosofsky1950
3Hart Bochner1956
4Ólafur Arnalds1986
5Abbey Lee1987

Conclusion

Javascript array objects are a versatile way of storing related values (or objects). Traversing the arrya is done by iterating over the values array[0] to array[array.length]. Sorting the contents of the array varies by type (numeric, alphabetic) and order (ascending, descending). A comparison function is needed for any sorting other than the default, ascending ASCII strings. This blog post has covered these ideas in a practical fashion, showing code snippets to implement each need.

(The topic of searching algorithms is far too deep and rich to go into here. The seminal work — highly and personally recommended — is Donald Knuth‘s Sorting and Searching, The Art of Computer Programming. 3 (2nd ed.), Addison-Wesley.)

Start Learning

To learn more about Javascript, check out other Javascript blog posts and enroll in our Javascript Nanodegree programs, including Intermediate Javascript.

Source Code

Complete source code, when needed to expand upon the snippets above, will be included below, ready for use in an online Javascript tester like PlayCode.