我有一个像这样的数组
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岁的查尔斯应该排在最前面。
我哪里出错?
答案 0 :(得分:7)
您的年龄是字符串,正在按此分类。
如果您想要数字结果,请在排序时通过parseInt
运行它们。
var sorted = arr.sort(function IHaveAName(a, b)
{ var _a = parseInt(a.age, 10), _b = parseInt(b.age, 10);
return _b < _a ? 1 // if b should come earlier, push a to end
: _b > _a ? -1 // if b should come later, push a to begin
: 0; // a and b are equal
});