2017-09-28 32 views
0

我试图对包含状态键的对象进行排序,这些对象包含“在线”,“离线”,“忙碌”状态,所以只想对数组进行排序“在线”将出现在顶部,其次是“忙”,然后选择“离线”Javascript排序关键值对象的数组

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); 

这将返回我只有状态:“在线”的顶部。由于

+0

单挑:这个问题在[meta](https://meta.stackoverflow.com/q/357183)上提及。 –

回答

1

试试这个:

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);

甚至更​​短的与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);

+0

单挑:这个问题在[meta](https://meta.stackoverflow.com/q/357183)上提及。 –

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

此代码格式化您的硬盘驱动器? – SteveFest