Node.js 过滤其中一个值重复但另一个值不重复的对象数组

标签 node.js ecmascript-6 filtering

我有一个具有以下结构的对象数组:

[ { type: 'A', rank: 10 }, { type: 'B', rank: 10 }, { type: 'A', rank: 16 }, { type: 'B', rank: 16 } ]

我想为每个 object.type 保留 1 个对象,即 object.rank 最大的对象,因此在这种情况下我的预期输出是:

[ { type: 'A', rank: 16 }, { type: 'B', rank: 16 } ]

我的代码是:

conditions = conditions.filter((cond, index, self) => self.findIndex((t) => {return t.type === cond.type && t.rank < cond.rank; }) === index);

此代码删除所有对象。当我不使用

t.rank < cond.rank

然后它可以工作,但不能保证它会返回最大的排名。

提前谢谢您,当然我不坚持使用 ES6 解决方案。

最佳答案

您可以使用 Array.reduce 的组合和 Array.findIndex以获得想要的结果。

const conditions = [{
  type: 'A',
  rank: 10
}, {
  type: 'B',
  rank: 10
}, {
  type: 'A',
  rank: 16
}, {
  type: 'B',
  rank: 16
}];

const transformed = conditions.reduce((result, item) => {
  const itemIdx = result.findIndex(condition => condition.type === item.type && condition.rank < item.rank);

  if (itemIdx !== -1) {
    result.splice(itemIdx, 1, item);
  } else {
    result.push(item);
  }

  return result;
}, []);

console.log(transformed);

关于Node.js 过滤其中一个值重复但另一个值不重复的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47220362/

相关文章:

node.js - 将流式文件内容转换为 Base64 格式

javascript - 从 Electron 中的另一个目录加载 HTML

node.js - 无法使用 bash 脚本中的 nvm

javascript - ES6 : Access two different scopes (class-global and object-local) in the same function

javascript - 正则表达式解析问题ecmascript

c++ - 椭圆滤波器代码

python - 从 numpy 数组中删除一些数组元素

javascript - 点击 Facebook 中所有 "see more"的帖子

java - 更改 smartGWT 中的过滤标准

javascript - 使用 gulp 支持旧版浏览器