2016-11-11 43 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