user2928010 user2928010 - 5 months ago 14
Javascript Question

Sort javascript array by multiple keys

I have an array of objects something like this

var itemArray = [
{
"name": "name1",
"flag": true,
},
{
"name": "name1",
"flag": false,
},
{
"name": "name2",
"flag": false,
},
{
"name": "name3",
"flag": true,
}
];


I am already sorting this by the name key using the following:

var sortedItems = sortByKey(itemArray, "name");

function sortByKey(array, key) {
return array.sort(function(a, b) {
var x = a[key];
var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});


How do i also sort it by the flag key alphabetically so the false flags appear before the true flags? (I can use a string instead of boolean on the flag property if this makes it simpler)

To clarify, what I am looking for is an array which would be returned like this for example:

[
{ name: "name_a", flag: false },
{ name: "name_a", flag: true },
{ name: "name_b", flag: false },
{ name: "name_b", flag: true},
{ name: "name_c", flag: true},
{ name: "name_d", flag: false},
]

Answer

var sortedItems = sortByKey(itemArray, "name");

function sortByKey(array, key) {
    return array.sort(function(a, b) {
        if(a[key] == b[key]) {
          return (a['flag'] ? -1 : 1);
        } else {
          var x = a[key];
          var y = b[key];
          return x.localeCompare(y);
        }
});
Comments