【问题标题】:How to merge an arbitrary number of arrays of object without duplicates? [closed]如何合并任意数量的对象数组而不重复? [关闭]
【发布时间】:2021-03-18 16:58:07
【问题描述】:

我已经对此进行了搜索,但解决方案希望您知道要合并多少个数组而不重复。

我必须循环一个包含任意数量数组的对象。 数组中的对象类型为{sType: string, nLaId: number, sname: string} 要确定一个对象是否重复,必须检查是否有另一个对象具有相同的sType AND nLaId

for(let key in objectContainingArrays){ // objectContainingArrays[key] is an array with specific objects of type {sType: string, nLaId: number, sname: string}
  // how would I merge the arrays here in the fastest way without duplicates?
}

如果解决方案很明显或者可以在另一个问题中找到解决方案,那么我很抱歉,我会很感激一个链接。谢谢!

【问题讨论】:

    标签: javascript arrays typescript merge duplicates


    【解决方案1】:

    如果您没有使用任何像 underscore.js 这样的库。您可以先连接数组,然后过滤掉重复项 -

    var mergedArray = [].concat.apply([], arrList);
    
    var uniqueArray = mergedArray.filter((currentValue, index, arr) => 
      arr.findIndex (
         arrItem => (
            arrItem.sType === currentValue.sType && arrItem.nLaId === currentValue.nLaId)
         ) === index
    );
    

    下面是一个示例 -

    var arr1 = [{
        sType: "S1",
        nLaId: 1,
        sname: "N1"
      },
      {
        sType: "S2",
        nLaId: 2,
        sname: "N2"
      },
      {
        sType: "S3",
        nLaId: 3,
        sname: "N3"
      }
    ];
    var arr2 = [{
        sType: "S2",
        nLaId: 2,
        sname: "N4"
      },
      {
        sType: "S2",
        nLaId: 2,
        sname: "N5"
      },
      {
        sType: "S1",
        nLaId: 3,
        sname: "N6"
      },
      {
        sType: "S4",
        nLaId: 3,
        sname: "N7"
      }
    ];
    var arr3 = [{
        sType: "S1",
        nLaId: 1,
        sname: "N8"
      },
      {
        sType: "S2",
        nLaId: 2,
        sname: "N9"
      }
    ];
    
    var arrList = [arr1, arr2, arr3];
    var mergedArray = [].concat.apply([], arrList);
    var uniqueArray = mergedArray.filter((currentValue, index, arr) => 
    arr.findIndex(arrItem => (arrItem.sType === currentValue.sType && arrItem.nLaId === currentValue.nLaId)) === index);
    
    console.log(uniqueArray);

    【讨论】:

    • 嘿,谢谢它确实有效。我去查下划线库,谢谢推荐
    猜你喜欢
    • 2021-09-11
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 2019-07-15
    • 1970-01-01
    相关资源
    最近更新 更多