Javascript:如何按其中一个字段中的值对记录数组进行排序?

发布于 2024-08-10 12:09:54 字数 419 浏览 2 评论 0原文

可能的重复:
按字段值对数组中的对象进行排序JavaScript

假设我有一个记录数组:[{a:0,b:0},{a:2,b:1},{a:1,b:2}] 我希望按每个记录中的 a 字段的降序排序,并将排序后的记录作为新数组进行提醒(即新数组将是 [{a:2,b: 1},{a:1,b:2},{a:0,b:0}]) - 我该怎么做?我尝试了几种方法,但我的头撞在墙上。

谢谢

Possible Duplicate:
Sorting objects in an array by a field value in JavaScript

Suppose I have an array of records: [{a:0,b:0},{a:2,b:1},{a:1,b:2}]
which I wish to sort in descending order of the a field in each record, and alert the sorted records as a new array (ie the new array would be [{a:2,b:1},{a:1,b:2},{a:0,b:0}]) - how would I go about this? I've tried a few approaches but am banging my head against the wall.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

飞烟轻若梦 2024-08-17 12:09:54

一种简单的方法

var sorted = [{a:0,b:0},{a:2,b:1},{a:1,b:2}].sort( function( a, b )
{
  if ( a.a == b.a ) return 0;
  return ( a.a > b.a ) ? 1 : -1;
}).reverse();

EDIT

和一种更灵活的方法

// Note: console.log() require Firebug

var records = [{a:0,b:0},{a:2,b:1},{a:1,b:2}];
console.log( records );

// Sorty by 'a' ascending
sortByProperty( records, 'a' );
console.log( records );

// Sort by 'b' descending
sortByProperty( records, 'b', true );
console.log( records );  

function sortByProperty( arr, property, descending )
{
  arr.sort( function( a, b )
  {
    return Boolean( descending )
      ? b[property] - a[property]
      : a[property] - b[property]
  } );
}

EDIT 2

也适用于字符串的版本

// Note: console.log() require Firebug

var records = [
    {a:0,b:0}
  , {a:2,b:1}
  , {a:'banana',b:'apple'}
  , {a:1,b:2}
  , {a:'apple',b:'banana'}
];
console.log( records );

// Sorty by 'a' ascending
sortByProperty( records, 'a' );
console.log( records );

// Sort by 'b' descending
sortByProperty( records, 'b', true );
console.log( records );  

function sortByProperty( arr, property, descending )
{
  arr.sort( function( a, b )
  {
    var c = a[property].toString()
      , d = b[property].toString()

    if ( c == d ) return 0;
    return Boolean( descending )
      ? d > c ? 1 : -1
      : d < c ? 1 : -1 
  } );
}

A straightforward approach

var sorted = [{a:0,b:0},{a:2,b:1},{a:1,b:2}].sort( function( a, b )
{
  if ( a.a == b.a ) return 0;
  return ( a.a > b.a ) ? 1 : -1;
}).reverse();

EDIT

And a more flexible approach

// Note: console.log() require Firebug

var records = [{a:0,b:0},{a:2,b:1},{a:1,b:2}];
console.log( records );

// Sorty by 'a' ascending
sortByProperty( records, 'a' );
console.log( records );

// Sort by 'b' descending
sortByProperty( records, 'b', true );
console.log( records );  

function sortByProperty( arr, property, descending )
{
  arr.sort( function( a, b )
  {
    return Boolean( descending )
      ? b[property] - a[property]
      : a[property] - b[property]
  } );
}

EDIT 2

A version that works for strings as well

// Note: console.log() require Firebug

var records = [
    {a:0,b:0}
  , {a:2,b:1}
  , {a:'banana',b:'apple'}
  , {a:1,b:2}
  , {a:'apple',b:'banana'}
];
console.log( records );

// Sorty by 'a' ascending
sortByProperty( records, 'a' );
console.log( records );

// Sort by 'b' descending
sortByProperty( records, 'b', true );
console.log( records );  

function sortByProperty( arr, property, descending )
{
  arr.sort( function( a, b )
  {
    var c = a[property].toString()
      , d = b[property].toString()

    if ( c == d ) return 0;
    return Boolean( descending )
      ? d > c ? 1 : -1
      : d < c ? 1 : -1 
  } );
}
古镇旧梦 2024-08-17 12:09:54

排序委托怎么样?

[{a:0,b:0},{a:2,b:1},{a:1,b:2}].sort(function(a,b){
    // see http://www.javascriptkit.com/javatutors/arraysort.shtml 
    // for an explanation of this next line
    return b.a-a.a;
});

(保存后,我注意到另外两个几乎相同的答案,但我将把我的答案留在这里,以了解细微的差别。)

How about a sort delegate?

[{a:0,b:0},{a:2,b:1},{a:1,b:2}].sort(function(a,b){
    // see http://www.javascriptkit.com/javatutors/arraysort.shtml 
    // for an explanation of this next line
    return b.a-a.a;
});

(After saving, I noticed two other almost identical answers, but I'll leave mine here for the minor differences.)

寂寞清仓 2024-08-17 12:09:54

使用闭包比直接引用函数慢。

// assume var records = [{a:0,b:0},{a:2,b:1},{a:1,b:2}];
records.sort(myCustomSort);
function myCustomSort(a, b) {
    return (b.a - a.a);
}

如果您确实需要新数组的第二个变量,只需在调用自定义排序方法之前复制初始数组即可。

Using closures is slower than directly referencing a function.

// assume var records = [{a:0,b:0},{a:2,b:1},{a:1,b:2}];
records.sort(myCustomSort);
function myCustomSort(a, b) {
    return (b.a - a.a);
}

If you really need a second variable for the new array, simply make a copy of the initial array prior to calling the custom sort method.

帅气称霸 2024-08-17 12:09:54
// your items array
var items = [{a:0,b:0},{a:2,b:1},{a:1,b:2}];
// function we can use as a sort callback
var compareItemsBy_a_Descending = function(x,y) {
  return y.a - x.a;
};
// function to alert the items array
var displayItems = function(items) {
  var out = [];
  for (var i=0;i<items.length;i++) {
    out.push('{a:' + items[i].a + ',b:' + items[i].b + '}');
  }
  alert('[' +out.join(',') + ']');
};

// run it
displayItems(items);

结果:[{a:0,b:0},{a:2,b:1},{a:1,b:2}]

// sort it
items.sort(compareItemsBy_a_Descending);

// run it again
displayItems(items);

结果:[{a:2 ,b:1},{a:1,b:2},{a:0,b:0}]

// your items array
var items = [{a:0,b:0},{a:2,b:1},{a:1,b:2}];
// function we can use as a sort callback
var compareItemsBy_a_Descending = function(x,y) {
  return y.a - x.a;
};
// function to alert the items array
var displayItems = function(items) {
  var out = [];
  for (var i=0;i<items.length;i++) {
    out.push('{a:' + items[i].a + ',b:' + items[i].b + '}');
  }
  alert('[' +out.join(',') + ']');
};

// run it
displayItems(items);

RESULT: [{a:0,b:0},{a:2,b:1},{a:1,b:2}]

// sort it
items.sort(compareItemsBy_a_Descending);

// run it again
displayItems(items);

RESULT: [{a:2,b:1},{a:1,b:2},{a:0,b:0}]

熊抱啵儿 2024-08-17 12:09:54

我的同事休斯今天刚刚向我展示了以下内容。
请注意使用 -cmp() 和 cmp() 进行降序和升序。

var cmp = function(x, y){ return x > y? 1 : x < y ? -1 : 0; },
    arr =  [{a:0,b:0},{a:2,b:1},{a:1,b:2},{a:2, b:2}];

// a ascending
arr.sort(function(x, y){
    return cmp(x.a, y.a) < cmp(y.a, x.a) ? -1:1;
});

// a descending
arr.sort(function(x, y){
    return -cmp(x.a, y.a) < -cmp(y.a, x.a) ? -1:1;
});

// a ascending, b descending
arr.sort(function(x, y){
    return [cmp(x.a, y.a), -cmp(x.b, y.b)] < [cmp(y.a, x.a), -cmp(y.b,x.b)] ? -1:1;
});

Hughes my colleague just showed me today the following.
Note the use of -cmp() and cmp() for descending and ascending.

var cmp = function(x, y){ return x > y? 1 : x < y ? -1 : 0; },
    arr =  [{a:0,b:0},{a:2,b:1},{a:1,b:2},{a:2, b:2}];

// a ascending
arr.sort(function(x, y){
    return cmp(x.a, y.a) < cmp(y.a, x.a) ? -1:1;
});

// a descending
arr.sort(function(x, y){
    return -cmp(x.a, y.a) < -cmp(y.a, x.a) ? -1:1;
});

// a ascending, b descending
arr.sort(function(x, y){
    return [cmp(x.a, y.a), -cmp(x.b, y.b)] < [cmp(y.a, x.a), -cmp(y.b,x.b)] ? -1:1;
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文