exhtml
7/3/2018 - 6:09 AM

Array sort snippets

Array.sort() method let’s you compare items in an array and sort them. You pass in a callback function that accepts two arguments: first and second item to compare. Array.sort() works by looping through each item in the array and comparing it to the one after it based on some criteria you specify in your comparison function.

  • If you return -1, it will place the first item before the second.
  • If you return 1, it will place the second item before the first.
  • If you return 0, it will leave them unchanged.

Notes:

  • With Array.sort(), if the letter comes later in the alphabet, it has a higher value than if it comes earlier.
  • If you omit the compare function, the sort() method sorts the elements with the sort order based on the Unicode code point values of elements.
  • the sort() method will convert the element to a string for sorting in case the type of the element is not the string.

Sort alphabetically:

animals.sort();

Sort alphabetically in descending order:

animals.sort(function (a, b) {
    if (a > b) {
        return -1;
    }
    if (b > a) {
        return 1;
    }
    return 0;
});

Sort an array that mixes lowercase and uppercase:

You need to convert all elements to the same for comparison:

mixedCaseAnimals.sort(function (a, b) {
    var x = a.toUpperCase(),
        y = b.toUpperCase();
    if (x > y) {
        return 1;
    }
    if (x < y) {
        return -1;
    }
    return 0;
});

Sort an array of strings with non-ASCII characters (é, è, etc.)

var animaux = ['zèbre', 'abeille', 'écureuil', 'chat'];

You need to use the localeCompare() method of the String object to compare strings in a specific locale:

animaux.sort(function (a, b) {
    return a.localeCompare(b);
});

Sort an array of numbers in ascending order

You need to pass in a custom compare function that compares two numbers.

scores.sort(function (a, b) {
    return a - b;
});

or

scores.sort((a, b) => a - b);

For descending order, reverse the logic:

scores.sort((a, b) => b - a);

Sort an array of objects by a specified property

var employees = [
    {name: 'John', salary: 90000, hireDate: "July 1, 2010"},
    {name: 'David', salary: 75000, hireDate: "August 15, 2009"},
    {name: 'Ana', salary: 80000, hireDate: "December 12, 2011"}
];

– Sort the employees by salary in ascending order.

employees.sort(function (x, y) {
    return x.salary - y.salary;
});

– Sort the employees by name:

employees.sort(function (x, y) {
    var a = x.name.toUpperCase(),
        b = y.name.toUpperCase();
    if (a > b) {
        return 1;
    }
    if (a < b) {
        return -1;
    }
    return 0;
});

– Sort employees by hire date: You first have to create a valid Date object from the date string, and then compare two dates, which is the same as comparing two numbers.

employees.sort(function (x, y) {
    var a = new Date(x.hireDate),
        b = new Date(y.hireDate);
    return a - b;
});

Sort an array based on two properties

First sort by an integer, next sort by a string: show the item with the most votes first, and then for items with the same number of votes, sort alphabetically.

[
    { title: 'Apple', votes: 1 },
    { title: 'Milk', votes: 2 },
    { title: 'Carrot', votes: 3 },
    { title: 'Banana', votes: 2 }
]

votes.sort(function (vote1, vote2) {

    // Sort by votes
    if (vote1.votes > vote2.votes) return -1; // If the first item has a higher number, move it down
    if (vote1.votes < vote2.votes) return 1; // If the first item has a lower number, move it up

    // If the votes number is the same between both items, sort alphabetically
    if (vote1.title > vote2.title) return 1; // If the first item comes first in the alphabet, move it up
    if (vote1.title < vote2.title) return -1; // Otherwise move it down

});

Optimizing JavaScript Array sort method

sort() method calls the compare function multiple times for each element in the array. We cannot reduce the number of times that compare function is executed. However, we can reduce the work that the comparison has to do. This technique is called Schwartzian Transform. To implement this, you follow these steps:

  1. First, extract the actual values into a temporary array using the map() method.
  2. Second, sort the temporary array with the elements that are already evaluated (or transformed).
  3. Third, walk the temporary array to get an array with the right order.
// temporary array holds objects with position
// and length of element
var lengths = rivers.map(function (e, i) {
    return {index: i, value: e.length };
});
 
// sorting the lengths array containing the lengths of
// river names
lengths.sort(function (a, b) {
    return +(a.value > b.value) || +(a.value === b.value) - 1;
});
 
// copy element back to the array
var sortedRivers = lengths.map(function (e) {
    return rivers[e.index];
});