Search code examples
javascriptarrayssortingobject

JavaScript sort an array of objects by property and alphabetically


var objs = [ 
    { status: 'Inactiv', name: 'Name_1' },
    { status: 'Extern',  name: 'Name_2' },
    { status: 'Inactiv', name: 'Name_3' },
    { status: 'Administrator', name: 'Name_3' },
    { status: 'All', name: 'Name_4' },
    { status: 'Up', name: 'Name_5' },
    { status: 'Inactiv', name: 'Name_6' },
];

I want to sort those items in such a way that the ones containing "Inactiv" to be first. I was trying with .sort(), but I don't know how exactly to use the parameters. The remaining list (without "status: Inactiv") to be sort alphabetically.


Solution

  • This should do the trick

    Edit: If you need the rest sorted alphabetically, you can use the code below instead

    var objs = [ 
        { status: 'Inactiv', name: 'Name_1' },
        { status: 'Extern',  name: 'Name_2' },
        { status: 'Inactiv', name: 'Name_3' },
        { status: 'Administrator', name: 'Name_3' },
        { status: 'All', name: 'Name_4' },
        { status: 'Up', name: 'Name_5' },
        { status: 'Inactiv', name: 'Name_6' },
    ];
      
     var sorted = objs.filter((obj) => obj.status == 'Inactiv').concat(objs.filter((obj) => obj.status != 'Inactiv').sort((x,y) => x.name > y.name ? 1 : -1))
    
    console.log(sorted);