如何根据对象属性的数值对对象数组进行排序?

时间:2013-06-11 06:17:56

标签: javascript node.js

我有一个像这样的数组

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岁的查尔斯应该排在最前面。

我哪里出错?

1 个答案:

答案 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
});