我正在使用纯javascript按降序排序对象数组。我最初认为JSON.stringify方法引起了问题,如[here] [1]所述。显然,JSON.stringify不会按设计保留对象的顺序。给出下面的对象数组我似乎得到一个随机排序顺序,使用下面的代码,我对对象数组进行排序,然后导出数组中第一个对象的权重属性。
var byWeight = objArray.slice(0);
var sorted = byWeight.sort(function(a,b) { return b.weight - a.weight; } );
sorted[0].something.weight;
在这段代码的不同运行中,我似乎随机得出.29或.35的权重。为什么会这样?
这是数组:
[
{
"something": {
"terms": [
{
"elements": {
"number": {
"span": [
9,
10
],
"value": "1"
}
},
"span": [
9,
12
],
"value": "1g",
"label": "grams"
}
],
"span": [
9,
12
],
"weight": 0.29,
"value": "1gm"
}
},
{
"something": {
"terms": [
{
"elements": {
"number": {
"span": [
16,
18
],
"value": "30"
}
},
"span": [
16,
20
],
"value": "30ml",
"label": "liters"
}
],
"span": [
16,
20
],
"weight": 0.35,
"value": "30ml"
}
}
]
答案 0 :(得分:1)
你有错误的参考。改变这个
Content-length
to(watch var sorted = byWeight.sort(function(a,b) { return b.weight - a.weight; } );
)
.something.
工作模式:
byWeight.sort(function (a, b) { return b.something.weight - a.something.weight; });

答案 1 :(得分:0)
你的objArray格式不佳,"术语"如果它包含键索引元素,例如" span"," value"," label'它应该是一个对象;然后你的排序看错了,它应该是a.something.weight
/ b.something.weight
。 jsfiddle.net/3qgtn9r1
var objArray = [
{
"something": {
"terms": {
"span": [
9,
12
],
"value": "1g",
"label": "grams"
},
"span": [
9,
12
],
"weight": 0.29,
"value": "1gm"
}
},
{
"something": {
"terms": {
"span": [
16,
20
],
"value": "30ml",
"label": "liters"
},
"span": [
16,
20
],
"weight": 0.35,
"value": "30ml"
}
}
];
var byWeight = objArray.slice(0);
var sorted = byWeight.sort(function(a,b) { return a.something.weight - b.something.weight; } );
console.log(sorted[0].something.weight);