Javascript sort array of objects on key values [duplicate]

I was trying to sort array of objects which contains status key which has "online","offline","Busy" , so just wanted to sort the array in such a way that all "online" would appear on top followed by "Busy" and then "offline"

var arr = [{_id: "58e21249", name: "test2", status: "offline"},
           {_id: "58e1249", name: "test3", status: "online"},
           {_id: "58qwe49", name: "test21", status: "offline"},
           {_id: "58ed49", name: "test212", status: "online"},
           {_id: "58ee49", name: "test23", status: "offline"},
           {_id: "58xe49", name: "test12", status: "online"},
           {_id: "5849", name: "test2323", status: "busy"},
           {_id: "58er49", name: "test2121", status: "busy"}];

arr.sort(function(first, second) {
   if (second.status == "online") return 1;

 });

console.log(arr);

This would return me only status: "online" on the top. Thanks

Answers:

Answer

Try this:

var arr = [{_id: "58e21249", name: "test2", status: "offline"},
           {_id: "58e1249", name: "test3", status: "online"},
           {_id: "58qwe49", name: "test21", status: "offline"},
           {_id: "58ed49", name: "test212", status: "online"},
           {_id: "58ee49", name: "test23", status: "offline"},
           {_id: "58xe49", name: "test12", status: "online"},
           {_id: "5849", name: "test2323", status: "busy"},
           {_id: "58er49", name: "test2121", status: "busy"}];
           
 var statusOrder = ["online", "busy", "offline"];
 
 arr = arr.sort(function(a, b) { 
     return statusOrder.indexOf(a.status) - statusOrder.indexOf(b.status);
 });

 console.log(arr);

And even shorter with ECMAScript6:

var arr = [{_id: "58e21249", name: "test2", status: "offline"},
           {_id: "58e1249", name: "test3", status: "online"},
           {_id: "58qwe49", name: "test21", status: "offline"},
           {_id: "58ed49", name: "test212", status: "online"},
           {_id: "58ee49", name: "test23", status: "offline"},
           {_id: "58xe49", name: "test12", status: "online"},
           {_id: "5849", name: "test2323", status: "busy"},
           {_id: "58er49", name: "test2121", status: "busy"}];
           
 var statusOrder = ["online", "busy", "offline"];
 
 arr = arr.sort((a, b) => statusOrder.indexOf(a.status) - statusOrder.indexOf(b.status));

 console.log(arr);

Answer
var statusOrder = ["online", "offline", "busy"];
arr.sort(function(first, second) {
    return statusOrder.indexOf(first.status) < statusOrder.indexOf(second.status);
});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.