我有一个这样的数组
var arr = [{ "name": "John", "age": "16" },
{ "name": "Charles", "age": "26" },
{ "name": "Charles", "age": "12" },
{ "name": "Charles", "age": "44" },
{ "name":"Charles", "age": "1" },
{ "name": "Charles", "age": "4"}]
我尝试的功能是
var sorted = yourArray.sort(function IHaveAName(a, b)
{ // non-anonymous as you ordered...
return b.age < a.age ? 1 // if b should come earlier, push a to end
: b.age > a.age ? -1 // if b should come later, push a to begin
: 0; // a and b are equal
});
获得的结果
[ { name: 'Charles', age: '1' },
{ name: 'Charles', age: '12' },
{ name: 'John', age: '16' },
{ name: 'Charles', age: '26' },
{ name: 'Charles', age: '4' },
{ name: 'Charles', age: '44' } ]
在那个 4 岁的查尔斯应该排在首位。
我哪里错了?