【问题标题】:Javascript - Get unique and sorted arrayJavascript - 获取唯一且排序的数组
【发布时间】:2020-09-06 21:59:47
【问题描述】:

我有一个包含重复项目的数组。我想过滤该数组以仅返回唯一项,但必须根据它们在初始数组中的次数对这些项进行排序

const initialArr = [
  {
    id: 1
  },
  {
    id: 1
  }, 
  {
    id: 2
  },
  {
    id: 1
  },
  {
    id: 3
  },
  {
    id: 3
  },
];

const expectedSortedResult = [
  {
    id: 1
  },
  {
    id: 3
  },
  {
    id: 2
  }
]

【问题讨论】:

标签: javascript arrays sorting filter


【解决方案1】:

无论离解决方案有多远,都尽量发布您的尝试。

您应该研究以下内容(我也用这些解决了它):

Reduce(创建对象、groupBy 并创建 __count 属性):https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Object.values()将其转换回数组,然后是

排序(按__count排序):https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

然后,如果您不希望在输出中使用该计数属性,则需要删除它,您可以使用 Map 执行此操作:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

const initialArr = [
  {id: 1},
  {id: 1}, 
  {id: 2},
  {id: 1},
  {id: 3},
  {id: 3},
];

const output = Object.values(initialArr.reduce((aggObj, item) => {      
  if (aggObj[item.id]){
    aggObj[item.id].__count += 1
  }
  else{
    aggObj[item.id] = item;
    aggObj[item.id].__count = 1
  }      
  return aggObj;
}, {}))
      .sort((a,b) => b.__count - a.__count)
      .map(a => {delete a.__count; return a});
      
      
console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    猜你喜欢
    • 2017-01-02
    • 2011-06-17
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多