2

我有一个这样的数组

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 岁的查尔斯应该排在首位。

我哪里错了?

4

1 回答 1

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
});
于 2013-06-11T06:20:32.053 回答