【问题标题】:Sort array of object for some keys in javascript对javascript中某些键的对象数组进行排序
【发布时间】:2016-09-01 18:27:21
【问题描述】:

我有一个对象数组。

[{
  id: 1,
  age: 23
}, {
  id: 1,
  age: 25
}, {
  id: 2,
  age: 230
}, {
  id: 2,
  age: 255
}, {
  id: 3,
  age: 232
}, {
  id: 1,
  age: 215
}]

我需要通过对每个 id 的最高年龄进行排序来获得最终数组。所以最终的数组将是。

[{
    id: 1,
    age: 215
  }, {
    id: 2,
    age: 255
  }, {
    id: 3,
    age: 232
  }]

【问题讨论】:

  • 你做了什么来尝试自己解决这个问题?
  • 这似乎没有排序。
  • 您想要的输出示例以什么方式排序?为什么会有重复的 ID?
  • 它只是样本数据。我只是简化了它,对于相同的 id,我们可以有不同的年龄值。

标签: javascript arrays sorting object


【解决方案1】:

您可以构建一个散列,在其中存储每个 id 具有最大年龄的对象。然后按数字对其键进行排序并按该顺序获取值。

var hash = array.reduce(function(hash, obj) {
  if(!hash[obj.id]) hash[obj.id] = obj;
  else if(hash[obj.id].age < obj.age) hash[obj.id] = obj;
  return hash;
}, Object.create(null));
Object.keys(hash).sort(function(a,b) {
  return a - b;
}).map(function(id) {
  return hash[id];
});

【讨论】:

    【解决方案2】:

    这里只有一个班轮

    var arr = [{
      id: 1,
      age: 23,
    }, {
      id: 1,
      age: 25,
    }, {
      id: 2,
      age: 230,
    }, {
      id: 2,
      age: 255,
    }, {
      id: 3,
      age: 232,
    }, {
      id: 1,
      age: 215,
    }],
    lut = {},
    res = arr.sort((a,b) => b.age - a.age).filter(o => lut[o.id] ? false : lut[o.id] = true).sort((a,b) => a.id - b.id);
    
    document.write("<pre>" + JSON.stringify(res,null,2) + "</pre>");

    【讨论】:

      【解决方案3】:

      您通常会使用 filterindexOfremove duplicate elements from an array。在数组元素是对象的情况下,你可以使用findIndex通过一些给定的属性值来搜索元素的索引。

      let result = [{
        id: 1,
        age: 23,
      }, {
        id: 1,
        age: 25,
      }, {
        id: 2,
        age: 230,
      }, {
        id: 2,
        age: 255,
      }, {
        id: 3,
        age: 232,
      }, {
        id: 1,
        age: 215,
      }].sort((a,b) => b.age - a.age)
      .filter((row,pos,self) => self.findIndex(item => item.id === row.id) === pos)
      .sort((a,b) => a.id - b.id);
      
      document.body.textContent = JSON.stringify(result);

      另外,你需要注意它的浏览器支持。

      【讨论】:

        【解决方案4】:

        或者这样避免使用lodash的uniq()方法:

        arr.sort(function(a,b){
          return b.id > a.id;
        }).reverse();
        var max = arr.length;
        var i = 0;
        while(i < max - 1){
          if (arr[i].id === arr[i+1].id) arr.splice(i+1,1);
          else i++
          max = arr.length;
        }
        

        【讨论】:

          【解决方案5】:

          您可以使用 vanillaJS 以这种方式进行排序。

          function sortByAgeDesc(a,b) {return a.age > b.age ? -1 : a.age === b.age ? 0 : 1;}
          
          
          output = input.sort(sortByAgeDesc);
          

          现在的问题是您只需要不同的 ID。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-12-23
            • 2017-04-15
            • 2021-10-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多