2017-09-28 8 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

これを試してみてください: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(function(a, b) { 
 
    return statusOrder.indexOf(a.status) - statusOrder.indexOf(b.status); 
 
}); 
 

 
console.log(arr);

そしてさらに短い:

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

関連する問題