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

헤드 업 :이 질문은 [메타] (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