【问题标题】:JS sort object by "x" in array [duplicate]JS按数组中的“x”对对象进行排序[重复]
【发布时间】:2014-04-27 06:14:46
【问题描述】:

我一直在为我的家庭照片开发一个小型社交照片共享网站(因为我们希望完全控制图像,本地托管是最好的)。我已经开发出完美运行并希望添加功能。

现在我所有的图像都是从 MySQL 中提取的:ROW -> object objects into array -> PHP -> JS array。数组看起来像

var 数组 = [{'key' = '1', 'title' = 'title', 'source' = 'path/to/image', 'album' = 'album}, ..]

在专辑标签内,它可能有不同的专辑名称,并且想根据专辑重新排序数组,我还没有想到可行的方法。

【问题讨论】:

  • 是json字符串吗?
  • @Andy 这个问题是关于对单个对象中的属性进行排序,而不是对对象数组进行排序。
  • 是的。我注意到。知道在某处有重复。

标签: javascript arrays sorting


【解决方案1】:

您可以使用Array.sort()

array.sort(function(a, b) {
    return a.album < b.album;
});

【讨论】:

    【解决方案2】:
    var array =  [
    {'key' :  '1', 'title' :  'title', 'source' :  'path/to/image', 'album' :  'album1'},
    {'key' :  '1', 'title' :  'title', 'source' :  'path/to/image', 'album' :  'album2'},
    {'key' :  '1', 'title' :  'title', 'source' :  'path/to/image', 'album' :  'album3'},
    {'key' :  '1', 'title' :  'title', 'source' :  'path/to/image', 'album' :  'album6'},
    {'key' :  '1', 'title' :  'title', 'source' :  'path/to/image', 'album' :  'album5'},
    {'key' :  '1', 'title' :  'title', 'source' :  'path/to/image', 'album' :  'album7'},
    {'key' :  '1', 'title' :  'title', 'source' :  'path/to/image', 'album' :  'album6'}
    ];
    
    array.sort(function(a,b){ return a.album > b.album;} );
    
    console.log(array);
    

    http://jsbin.com/xefujehe/1/

    【讨论】:

      【解决方案3】:

      在 MDN 上查看 Array.prototype.sort 的文档。

      这个方法有一个比较函数。这是一个例子:

      function compare(a, b) {
        if (a is less than b by some ordering criterion)
           return -1;
        if (a is greater than b by the ordering criterion)
           return 1;
        // a must be equal to b
        return 0;
      }
      

      以下是按专辑名称排序的方法:

      var albums = [
      {
          key: 110000,
          album: 'Starry nights'
      }, {
          key: 100,
          album: 'Zebra kills Zebra'
      }, {
          key: 1,
          album: 'Alfred Hitcock Presents'
      }, {
          key: 50,
          album: 'baby whales'
      }];
      
      albums.sort(function(a, b){
          return a.album === b.album ? 0 : a.album > b.album;
      });
      
      console.log(albums);
      

      jsfiddle.

      在排序时注意所有capital letters come before all lowercase letters

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-27
        • 2016-11-25
        • 1970-01-01
        • 2020-10-11
        • 2015-02-25
        • 1970-01-01
        • 2014-09-17
        • 2014-08-04
        相关资源
        最近更新 更多