首页 > 解决方案 > 根据 2 列比较 2 个不同的列表

问题描述

我正在尝试基于 2 个不同的列比较 2 个列表并获得差异。

const list1 = [[121,"7/2/2019"], [131,"7/22/2019"], [141, ]]
const list2 = [[121, ], [131, ], [141, ]]

在上面的 2 个列表中,我试图根据 2 列 - col1 和 col2 比较 list1 和 list2。两个列表中的第一列 (col1) [121,131,141] 将始终相同。

对于list1中的每个唯一列1(col1)[121,131,141],根据第二列比较list2中的相应元素,如果不同,我试图将其输出到不同的列表

Result = [[121,"7/2/2019"], [131,"7/22/2019"]

另一个例子是

const list1 = [[121,"7/2/2019"], [131,"7/22/2019"], [141, ]]
const list2 = []

Result = [[121,"7/2/2019"], [131,"7/22/2019"], [141, ]]

我尝试使用下面的代码,但它没有产生我想要的结果

const obj1 = list1.reduce((o, e) => Object.assign(o, {[e]: true}), {});
const obj2 = list2.reduce((o, e) => Object.assign(o, {[e]: true}), {});
const list3 = list2.filter(e => !obj1[e]); 
const list4 = list2.concat(list1.filter(e => !obj2[e])); 

任何线索/建议将不胜感激。

标签: loopsgoogle-apps-scriptcomparison

解决方案


试试这个来比较行与出现在各自数组中相同位置list1的行:list2

const difference = list1.filter((row, index) => row[1] !== list2[index][1]);

如果不能保证行出现在同一位置,请尝试以下操作:

  const list1 = [[121, "7/2/2019"], [131, "7/22/2019"], [141,]];
  const list2 = [[121,], [131,], [141,]];
  const difference = list1.filter((row1, index) => {
    const list2row = list2.filter(row2 => row2[0] === row1[0])[0];
    return !Array.isArray(list2row) || row1[1] !== list2row[1];
  });

推荐阅读