2016-11-11 74 views
3

我有一個數組,看起來是這樣的:排序的對象數組由兩個不同的標準

 var arr = [{user: '3', cash: 2}, 
     {user: 'tim', cash: 3}, 
     {user: '5', cash: 2}, 
     {user: 'noah', cash: 3}] 

我由高收入者這樣的排序是:

arr.sort(function (a, b) { 
    return b.tS - a.tS; 
}); 

它工作正常,但在我用最高的現金對這些傢伙進行排序後,我還想按用戶字段按字母順序排序每個人。請記住,有些用戶可能有數字,但是字符串類型(不是數字)。

我不能使用圖書館,我寧願它的工作速度快儘可能機明智的。

+0

簡單的方法:排序兩次,確保第二個排序是穩定的。 – dandavis

+0

我得到它的工作由於龔如心,但也有一個辦法\t 現金,然後由他們在最初的順序來安排他們呢? (如果諾亞與現款3系和上面的「3」移動以現金2最後一個索引,他應該是低於添這也與現款3) – user1938653

+0

是,尋找到一個「穩定的排序JS」;它不直觀簡單。 – dandavis

回答

4

你可以鏈中的排序標準。

的鏈接工程的每一步其中前者增量爲零。然後,如果值不等於零,則評估下一個增量或比較函數並提前返回。

在這裏,只有兩個排序組是返回的值,但對於更長的鏈,未來做出比較。

var arr = [{ user: '3', cash: 2 }, { user: 'tim', cash: 3 }, { user: '5', cash: 2 }, { user: 'noah', cash: 3 }]; 
 

 
arr.sort(function (a, b) { 
 
    return b.cash - a.cash || a.user.localeCompare(b.user); 
 
}); 
 

 
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }

要獲得與指數的排序,你需要索引存儲在臨時數組,並使用sorting with map

var array = [{ user: '3', cash: 2 }, { user: 'tim', cash: 3 }, { user: '5', cash: 2 }, { user: 'noah', cash: 3 }]; 
 

 
// temporary array holds objects with position and sort-value 
 
var mapped = array.map(function(el, i) { 
 
    return { index: i, cash: el.cash }; 
 
}); 
 

 
// sorting the mapped array containing the reduced values 
 
mapped.sort(function(a, b) { 
 
    return b.cash - a.cash || a.index - b.index; 
 
}); 
 

 
// container for the resulting order 
 
var result = mapped.map(function(el){ 
 
    return array[el.index]; 
 
}); 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

+0

有也是一種方式以現金,然後由他們在最初的順序來安排他們呢? (索引) – user1938653

+0

是的,但與地圖排序。請參閱編輯。 –

+0

我得到它的工作,但有一個更清潔和更短的路機器明智?順便說一句感謝短 – user1938653