【问题标题】:Get unique values from an array of objects based on two keys根据两个键从对象数组中获取唯一值
【发布时间】:2018-06-18 16:19:12
【问题描述】:

我有以下对象数组:

[{x: "1", y: "2", test: "9.000", class: "low-latency"},
{x: "2", y: "3", test: "9.000", class: "low-latency"},
{x: "22", y: "22", test: "0.000", class: "low-latency"},
{x: "22", y: "22", test: "127.000", class: "high-latency"},
{x: "5", y: "6", test: "96.000", class: "high-latency"},
{x: "6", y: "7", test: "66.000", class: "low-latency"},
{x: "7", y: "8", test: "71.000", class: "high-latency"}]

这是 react reducer 的一部分,因此它会根据从套接字返回的数据每 x 秒更新一次。

我需要做的是确保当 x 和 y 具有相同的值时 - 应该只有其中之一。实现这一目标的最佳方法是什么?

【问题讨论】:

  • 列表更新时不能这样做吗?那将是最有效的方法。事后才这样做会不太理想。
  • 另外,我假设您实际上需要改变原始数组而不是创建一个新的过滤数组,因为它似乎是共享的。对吗?
  • 是的,没错……

标签: javascript arrays object ecmascript-6 lodash


【解决方案1】:

最简单的方法是使用_.uniqBy 和哈希,例如。

_.uniqBy(arr, ({x,y}) => x+':'+y)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    相关资源
    最近更新 更多