Sort
Imagine a million lines of text—with no sorting it is impossible to find a certain line. But with sorting it can be easily located.
In Node.js we discover a sort method on arrays. This method can receive a function that determines how elements are sorted. With no arguments, it sorts in an ascending order.
Here we introduce an array called "patterns" that has 3 strings in it. We then invoke sort()
on our patterns array.
string
"abc" comes first as it is the earliest alphabetically.var patterns = ["def", "xyz", "abc"]; // Sort the string array. patterns.sort(); console.log("SORTED: " + patterns);SORTED: abc,def,xyz
We can assign a variable to the result of sort()
but there is no point to this. Sort()
modifies the existing array.
var patterns = ["def", "xyz", "abc"]; var result = patterns.sort(); // The original array is sorted. console.log("VARIABLE 1: " + patterns); console.log("VARIABLE 2: " + result);VARIABLE 1: abc,def,xyz VARIABLE 2: abc,def,xyz
In most programming languages numbers are sorted as numbers. But in JavaScript we find that numbers are sorted as strings. So 10 comes before 2 because 1 comes before 2.
override
the default sorting behavior with a function. In our function "compare" we sort two integers by their difference.var numbers = [-1, 100, 10, 1, 2, 3]; // Numbers are sorted as strings by default. numbers.sort(); console.log("SORT 1: " + numbers); // This function sorts numbers. // ... We compare two numbers by subtracting one from the other. var compare = function(a, b) { return a - b; }; // Sort numbers in a numeric way. numbers.sort(compare); console.log("SORT 2: " + numbers);SORT 1: -1,1,10,100,2,3 SORT 2: -1,1,2,3,10,100
LocaleCompare
The localeCompare
method handles non-ASCII characters (like those with accents) in a correct way. It should be used when sorting strings.
localCompare
to sort a string
array from low to high (in ascending alphabetical order).string
sort. We compare the second string
to the first in reverseAlphabetical
.reverse()
after sorting a string
array. But with localeCompare
we can directly sort in reverse order.var unsorted = ["def", "xyz", "ghi", "abc"]; function alphabetical(a, b) { // Use localeCompare. return a.localeCompare(b); } function reverseAlphabetical(a, b) { // Use localeCompare with second compared to first. return b.localeCompare(a); } // Sort in alphabetical order. unsorted.sort(alphabetical); console.log("LOCALECOMPARE 1: " + unsorted); // Sort in reverse alphabetical order. unsorted.sort(reverseAlphabetical); console.log("LOCALECOMPARE 2: " + unsorted);LOCALECOMPARE 1: abc,def,ghi,xyz LOCALECOMPARE 2: xyz,ghi,def,abc
Arrays are common in Node programs—we use them everywhere. With sort()
we change the ordering of elements in arrays to conform to a pattern.