DEV Community

Banesa Guaderrama
Banesa Guaderrama

Posted on

JavaScript Sort Array Sorting Arrays of Strings in JavaScript

alt text

Sorting Arrays of Strings

In JavaScript arrays have a sort( ) method that sorts the array items into an alphabetical order.

The following illustrates the syntax of the sort( )method:

Array.sort([comparer])

The sort( ) method accepts an optional argument which is a function that compares two elements of the array.

If the compare function is omitted, then the sort( ) method will sort the element based on the elements values.

Elements values rules:

1.If compare (a,b) is less than zero, the sort( ) method sorts a to a lower index than b. In other words, a will come first.
2.If compare (a,b) is greater than zero, the sort( ) method sort b to a lower index than a, i.e., b will come first.
3.If compare (a,b) returns zero, the sort ( ) method considers a equals b and leaves their positions unchanged.

Also, note that the sort( ) method accepts two arguments and will return a value that determines the sort order, the following represents the syntax:

function compare (a, b) {
   / …
}

Note: Remember that a function can be named as you want, but try to make the name meaningful to what you are trying to said through that function for an easy reference.

Sorting Arrays of Strings
Let's practice with an array of string named animals, as follows:

var animals = [
    'cat', 'dog', 'elephant', 'bee', 'ant'
];

To sort the elements of the animals array in ascending order alphabetically, we need to use the sort( ) method without passing the compare function as in the example:

animals.sort();
console.log(animals);
// ["ant", "bee", "cat", "dog", "elephant"]

To sort the animals array in descending order, you will need to change the logic of the compare function and pass it to the sort( ) method as the following example.

// descending order
animals.sort(function (a, b) {
    if (a > b) {
        return -1;
    }
    if (b > a) {
        return 1;
    }
    return 0;
});
console.log(animals);
// ["elephant", "dog", "cat", "bee", "ant"]

Of course, this is only a tiny piece of sorting array elements because we can use the sort( ) method also to sort by upper and lower case, numbers, and objects by property.

Top comments (7)

Collapse
 
krofdrakula profile image
Klemen Slavič • Edited

There's a big caveat to this method of string sorting: it doesn't take Unicode and non-English alphabets into account. Depending on your application, you might want to consider using the String::localeCompare() instead which has built-in support for things like language-specific sort ordering, ignoring cases or diacritics:

const strings = ['č','é','A','b','Đ'];

const defaultSort = Array.from(strings).sort();

const simpleSort = Array.from(strings).sort((a, b) => a - b);

const localeSort = Array.from(strings).sort((a, b) => {
  return a.localeCompare(b, 'en', { sensitivity: 'base' });
});

console.log(defaultSort);
console.log(simpleSort);
console.log(localeSort);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
charlesmwray profile image
Charles Wray

Love this reply. It's exactly what I was looking for. I do want to comment that there is a typo in case someone else tries to use this like I did and it didnt work. In the localeSort variable assignment it should be

return a.localeCompare(b, 'en', { sensitivity: 'base' });

Collapse
 
ricardorien profile image
Ricardo Aguilar

Thanks! both anwser are awesome!

Collapse
 
maprangsoft profile image
Maprangsoft

thank you.

Collapse
 
christophdellavalle profile image
christophdellavalle

I know it is an extension of the topic... How can I add an argument to the callback-function? I want to sort Objects according to their properties.

example of not working dummy code:
var sortprop='weight';
animals.sort(function (a, b, sortprop){....});

Collapse
 
ferdiesletering profile image
Ferdie Sletering

Use a compare closure function.

const data = [ {name: 'Bob', age: 22 }, { name: 'Jason', age:33 }];
const newData = data.sort( compare('name') )

function compare(prop) {
    return function (a,b) {
    console.log(prop) // outputs -> name
    return -1; // sort stuff
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
maprangsoft profile image
Maprangsoft

thank you.