【问题标题】:Reducing a 2D array taking into account another 2D array考虑另一个 2D 数组来减少 2D 数组
【发布时间】:2020-05-04 23:38:27
【问题描述】:

我有两个具有相同元素但顺序不同的二维数组。我想过滤一个考虑到它是否已经存在于第二个数组中。 两个数组的例子:

const firstArray = [['45614726','2020-4-28'],['45610125','2020-4-28'],['45880944','2020-4-28'],['43452341','2020-4-28']] // there are like 40 arrays inside, not sorted

const secondArray = [['34347896', '2020´4-30'],['45614726','2020-4-28'],['45610125','2020-4-28'],['45880944','2020-4-28'],['45892916','2020-4-28']] // there are like 300 arrays inside, not sorted

我想消除“firstArray”中第一个索引重复的“secondArray”数组。

secondArray =[['34347896', '2020´4-30'], ['45892916','2020-4-28']]

我尝试了几件事,我知道最有用的操作是使用 .reduce 但似乎我无法使其工作。

const notPosted = secondArray.reduce((a, b) => {
                if (!firstArray[a[0]]) a.different.push(b);
                return a;
            }, {different: []});

谢谢!

【问题讨论】:

  • 你必须在数组中查找,使用array.find

标签: javascript arrays node.js


【解决方案1】:

我不知道哪个更快:

const arr1 = [['45614726','2020-4-28'],['45610125','2020-4-28'],['45880944','2020-4-28'],['43452341','2020-4-28']]

const arr2 = [['34347896', '2020´4-30'],['45614726','2020-4-28'],['45610125','2020-4-28'],['45880944','2020-4-28'],['45892916','2020-4-28']];

//First solution:
console.log("1) ",arr2.filter(e=>!arr1.some(e2=>JSON.stringify(e2)==JSON.stringify(e))))

//Second:
console.log("2) ",arr2.filter(e=>!arr1.some(e2=>e[0]==e2[0]&&e[1]==e2[1])))

【讨论】:

    【解决方案2】:

    您可以将您的二维数组转换为一个对象,其中每个嵌套数组的零索引是键,第一个索引是值。 (即,您已经拥有适合此 [[key, val], [key, val], ...] 的完美形式的数组)

    Object.fromEntries(firstArray); 这很容易

    然后你在你的第二个数组上调用一个简单的过滤函数并只返回那些键不在对象中的那些(对象中键的查找速度很快 - 哈希表)

    // there are like 40 arrays inside, not sorted
    const firstArray = [['45614726','2020-4-28'],['45610125','2020-4-28'],['45880944','2020-4-28'],['43452341','2020-4-28']]
    
    // there are like 300 arrays inside, not sorted
    const secondArray = [['34347896', '2020´4-30'],['45614726','2020-4-28'],['45610125','2020-4-28'],['45880944','2020-4-28'],['45892916','2020-4-28']];
    
    const firstObj = Object.fromEntries(firstArray);
    
    const secondFiltered = secondArray.filter(([key,val]) => !firstObj.hasOwnProperty(key));
    
    console.log(secondFiltered);

    【讨论】:

      猜你喜欢
      • 2019-03-20
      • 2022-07-08
      • 1970-01-01
      • 1970-01-01
      • 2014-08-31
      • 2016-04-30
      • 1970-01-01
      • 1970-01-01
      • 2022-11-19
      相关资源
      最近更新 更多