2016-12-27 68 views
0

所以我有一個數組,我需要按照以下順序對狀態進行排序,即失敗 - >警告 - >完成。 通常,我使用lodash進行排序,但它的複雜順序在這裏。它還需要按運行排序後進行排序。我不知道該如何開始。如何根據其狀態跟其他字段自定義排序數組?

var arr = [{"status":"failure","name":"one","run":1}, 
{"status":"failure","name":"two","run":2}, 
{"status":"warn","name":"three","run":1}, 
{"status":"warn","name":"four","run":2}, 
{"status":"completed","name":"five","run":1}] 
+0

只是一個建議,我首先修改陣列包括一個單獨的statusId場,它以您想要的順序具有相應的整數。即故障= 1,警告= 2,完成= 3等,並按此排序。 – Illuminati

+0

Thakk你的建議,解決它通過這樣做。 – user3840211

回答

0

這樣的事情?

  1. 爲您的排序鍵添加一個額外的屬性。
var arrnew = arr.map(function(item){ 
    switch(item.status){ 
    case "failure": 
    item.statusId=1; 
    break; 
    case "warn": 
    item.statusId=2;} 
    //... 
    return item}); 
  • 排序通過使用
  • _.sortBy(arrnew, 'statusId');

    0

    排序基於「狀態」,然後通過「運行」的1或2中的子片段:

    let status_vals = [ "failure", "warn", "completed" ]; 
    
    let arr = [ 
        {"status":"failure","name":"one","run":1}, 
        {"status":"failure","name":"two","run":2}, 
        {"status":"warn","name":"three","run":1}, 
        {"status":"warn","name":"four","run":2}, 
        {"status":"completed","name":"five","run":1} 
    ]; 
    
    function sortIt (status_arr, sort_arr) { 
    
        let sorted_arr = []; 
        status_arr.forEach (d => { 
        let temp = arr.filter (obj => { 
         return obj.status === d; 
        }); 
    
        var length = temp.length; 
        for (var i = 0; i < length; i++) { 
         if (temp [ 0 ].run > temp [ i ].run) { 
         temp.push (temp.shift ()); 
         } 
        } 
    
        sorted_arr = [ ...sorted_arr, ...temp ]; 
        }); 
    
        return sorted_arr; 
    } 
    
    sortIt (status_vals, arr);