繁体   English   中英

考虑另一个 2D 数组来减少 2D 数组

[英]Reducing a 2D array taking into account another 2D array

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

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”的 arrays。

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

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

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

谢谢!

我不知道哪个更快:

 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])))

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

这很容易使用Object.fromEntries(firstArray);

Then you call a simple filter function on your second array and return only those that have a key that is not in the object (lookups of keys in an object are fast - hash tables)

 // 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM