[javascript] How do you sort an array on multiple columns?

I suggest to use a built in comparer and chain the wanted sort order with logical or ||.

function customSort(a, b) {
    return a[3].localeCompare(b[3]) || a[1].localeCompare(b[1]);
}

Working example:

_x000D_
_x000D_
var array = [_x000D_
    [0, 'Aluminium', 0, 'Francis'],_x000D_
    [1, 'Argon', 1, 'Ada'],_x000D_
    [2, 'Brom', 2, 'John'],_x000D_
    [3, 'Cadmium', 3, 'Marie'],_x000D_
    [4, 'Fluor', 3, 'Marie'],_x000D_
    [5, 'Gold', 1, 'Ada'],_x000D_
    [6, 'Kupfer', 4, 'Ines'],_x000D_
    [7, 'Krypton', 4, 'Joe'],_x000D_
    [8, 'Sauerstoff', 3, 'Marie'],_x000D_
    [9, 'Zink', 5, 'Max']_x000D_
];_x000D_
_x000D_
array.sort(function (a, b) {_x000D_
    return a[3].localeCompare(b[3]) || a[1].localeCompare(b[1]);_x000D_
});_x000D_
_x000D_
document.write('<pre>');_x000D_
array.forEach(function (a) {_x000D_
    document.write(JSON.stringify(a) + '<br>');_x000D_
});
_x000D_
_x000D_
_x000D_

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to algorithm

How can I tell if an algorithm is efficient? Find the smallest positive integer that does not occur in a given sequence Efficiently getting all divisors of a given number Peak signal detection in realtime timeseries data What is the optimal algorithm for the game 2048? How can I sort a std::map first by value, then by key? Finding square root without using sqrt function? Fastest way to flatten / un-flatten nested JSON objects Mergesort with Python Find common substring between two strings

Examples related to sorting

Sort Array of object by object field in Angular 6 Sorting a list with stream.sorted() in Java How to sort dates from Oldest to Newest in Excel? how to sort pandas dataframe from one column Reverse a comparator in Java 8 Find the unique values in a column and then sort them pandas groupby sort within groups pandas groupby sort descending order Efficiently sorting a numpy array in descending order? Swift: Sort array of objects alphabetically