Leo*_*oni 54 javascript arrays sorting
我有一个要排序的对象数组.每个对象有两个参数:强度和名称
objects = []
object[0] = {strength: 3, name: "Leo"}
object[1] = {strength: 3, name: "Mike"}
Run Code Online (Sandbox Code Playgroud)
我想首先按强度排序,然后按名称按字母顺序排序.我使用以下代码按第一个参数排序.我如何排序呢?
function sortF(ob1,ob2) {
if (ob1.strength > ob2.strength) {return 1}
else if (ob1.strength < ob2.strength){return -1}
return 0;
};
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助.
Mat*_*att 83
扩展您的排序功能是这样的;
function sortF(ob1,ob2) {
if (ob1.strength > ob2.strength) {
return 1;
} else if (ob1.strength < ob2.strength) {
return -1;
}
// Else go to the 2nd item
if (ob1.name < ob2.name) {
return -1;
} else if (ob1.name > ob2.name) {
return 1
} else { // nothing to split them
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
A <和>字符串的比较是字母比较.
geo*_*org 49
当按多个键排序时,这个小功能通常很方便:
cmp = function(a, b) {
if (a > b) return +1;
if (a < b) return -1;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
或者,更简洁地说,
cmp = (a, b) => (a > b) - (a < b)
Run Code Online (Sandbox Code Playgroud)
像这样应用:
array.sort(function(a, b) {
return cmp(a.strength,b.strength) || cmp(a.name,b.name)
})
Run Code Online (Sandbox Code Playgroud)
Javascript确实缺少Ruby的宇宙飞船运营商,这使得这种比较非常优雅.
Nin*_*olz 22
您可以使用逻辑OR链接排序顺序.
objects.sort(function (a, b) {
return a.strength - b.strength || a.name.localeCompare(b.name);
});
Run Code Online (Sandbox Code Playgroud)
当我在寻找这个问题的答案时,我在StackOverflow上找到的答案并不是我所希望的.所以我创建了一个简单,可重用的函数来完成这个.它允许您使用标准的Array.sort,但使用firstBy().thenBy().thenBy()样式. https://github.com/Teun/thenBy.js
PS.这是我第二次发布这个.主持人第一次删除了"请不要为自己的工作制作宣传帖子".我不确定这里的规则是什么,但我试图回答这个问题.我很抱歉这是我自己的工作.请随意删除,但请指出我所涉及的规则.
史蒂夫的回答,但更漂亮。
objects.sort(function(a,b)
{
if(a.strength > b.strength) {return 1;}
if(a.strength < b.strength) {return -1;}
if(a.name > b.name ) {return 1;}
if(a.name < b.name ) {return -1;}
return 0;
}
Run Code Online (Sandbox Code Playgroud)