从基于两个键的对象数组中获取唯一值

时间:2018-01-09 15:25:30

标签: javascript arrays object ecmascript-6 lodash

我有以下对象数组:

[{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"}]

这是反应减速器的一部分,因此根据从套接字返回的数据,每隔x秒更新一次。

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

您可以使用filter来完成此任务:

arr = arr.filter(function(a) {
  var key = a.x + '|' + a.y;
  if (!this[key]) {
    this[key] = true;
    return true;
  }
}, Object.create(null));

var arr = [{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"}]

arr = arr.filter(function(a) {
  var key = a.x + '|' + a.y;
  if (!this[key]) {
    this[key] = true;
    return true;
  }
}, Object.create(null));
console.log(arr)

相关问题