如果我有一系列这样的位置:
["Roberts", "baltimore", "Maryland", "21212"],
["Adams", "baltimore", "Maryland", "21212"],
["Joes", "philadelphia", "Pennsylvania", "30333"],
["Carls", "new york", "New York", "40415"]
使用Javascript或Jquery,我将如何按状态排序,然后按名称排序,因此生成的顺序为:
["Adams", "baltimore", "Maryland", "21212"],
["Roberts", "baltimore", "Maryland", "21212"],
["Carls", "new york", "New York", "40415"],
["Joes", "philadelphia", "Pennsylvania", "30333"]
答案 0 :(得分:3)
如果我们从实际数组开始:
var orig = [
["Roberts", "baltimore", "Maryland", "21212"],
["Adams", "baltimore", "Maryland", "21212"],
["Joes", "philadelphia", "Pennsylvania", "30333"],
["Carls", "new york", "New York", "40415"]
];
我们可以这样排序:
var sorted = orig.sort(
function(a, b) {
// compare states
if (a[2] < b[2])
return -1;
else if (a[2] > b[2])
return 1;
// states were equal, try names
if (a[0] < b[0])
return -1;
else if (a[0] > b[0])
return 1;
return 0;
}
);
返回:
[
["Adams","baltimore","Maryland","21212"],
["Roberts","baltimore","Maryland","21212"],
["Carls","new york","New York","40415"],
["Joes","philadelphia","Pennsylvania","30333"]
]
答案 1 :(得分:0)
尝试这个答案(见最后),但需要一个明确的自定义标准:
“”“比较(object1,object2)
if object1.state&gt; object2.state然后object1更大(1)
if object1.state&lt; object2.state然后object2更大(-1)
if object1.name&gt; object2.name然后object1更大(1)
if object1.name&lt; object2.name然后object2更大(-1)
对象是相同的,或者至少不能按照您暴露的标准进行排序
“”“
How to sort an array of objects with jquery or javascript
(请注意,array.sort中的“array”是指您的对象数组,并且如果您的对象实际上具有字段名称“name”和“state”,因为您实际上没有指定它们 - 实际上它们没有字段,所以它们不是对象也不是数组。)