loops - 根据 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]));
任何线索/建议将不胜感激。
解决方案
试试这个来比较行与出现在各自数组中相同位置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];
});
推荐阅读
- javascript - 如何在没有 document.getElementById('..') 的情况下获取输入(文本)字段的值
- java - GPay InAppSubscription SetSku详情
- google-apps-script - 使用 Apps 脚本访问 tumblr API 时遇到问题
- html - 如何将文本放置在居中(水平和垂直)内部的图像下方
- azure - 在 Azure 数据工厂概览页面中看不到作者和监控卡
- node.js - mongodb / mongoose 子文档聚合查询
- javascript - 在 render 中使用 const 存储状态值的意义
- python - 如何解决以元组为值的嵌套字典的性能问题?
- loops - 如何让用户选择是否要继续使用该程序?如果用户不使用,是否会显示“Thankyou for using”?
- postgresql - 将多维数组插入 Postgres