代码之家  ›  专栏  ›  技术社区  ›  ScalaBoy

如何从对象数组中删除重复记录?

  •  0
  • ScalaBoy  · 技术社区  · 6 年前

    我在javascript中有这个对象。

    [{"col1": 1, "col2": 25},{"col1": 1, "col2": 25},{"col1": 3, "col2": 30}]
    

    如何删除重复记录以获得此结果?

    [{"col1": 1, "col2": 25},{"col1": 3, "col2": 30}]
    

    我试过下一个逻辑,但不起作用:

    [...new Set(myData)]
    
    3 回复  |  直到 6 年前
        1
  •  1
  •   Shidersz    6 年前

    我最近在另一个答案上读到了这个,我喜欢它,这使用了 filter() 作为 this 在过滤器功能中。

    const input = [
        {"col1": 1, "col2": 25},
        {"col1": 1, "col2": 25},
        {"col1": 3, "col2": 30}
    ];
    
    let res = input.filter(function({col1, col2})
    {
        return !this.has(`${col1}-${col2}`) && this.add(`${col1}-${col2}`)
    }, new Set());
    
    console.log(res);
        2
  •  1
  •   quirimmo    6 年前

    const a = [{"col1": 1, "col2": 25},{"col1": 1, "col2": 25},{"col1": 3, "col2": 30}];
    
    console.log(
      a.reduce(
        (acc, val) => !acc.some(({col1, col2}) => val.col1 === col1 && val.col2 === col2) 
                      ? acc.concat(val) 
                      : acc, 
         []
      )
    );
        3
  •  1
  •   Jack Bashford    6 年前

    This answer 显示简单 filter 操作 Set :

    const data = [{"col1": 1, "col2": 25},{"col1": 1, "col2": 25},{"col1": 3, "col2": 30}];
    
    const unique = data.filter(function({ col1, col2 }) { return !this.has(`${col1}-${col2}`) && this.add(`${col1}-${col2}`)}, new Set);
    
    console.log(unique);