gpt4 book ai didi

javascript - 使用 jQuery 或 JavaScript 使用另一个数组过滤数组

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:42:24 24 4
gpt4 key购买 nike

我正在尝试使用来自另一个数组“outputdata”的键值过滤数组“arrSOPrecods”。第一个数组 'arrSOPrecods' 包含要针对特定​​ SOP 进行培训的用户的记录 第二个数组 'outputdata' 包含已针对特定 SOP 进行培训的用户的记录 我需要从 arrSOprecords 中过滤掉输出数据中存在的记录。我尝试了许多不同的方法,例如 jQuery 过滤器、JavaScript for 循环以及它自己的 .filter 函数,但进展甚微,但没有任何用处。这是数据示例以及最终输出应该是什么。

var arrSOPrecords = [
{ User: "Cesar", SOP: "training 1" },
{ User: "Cesar", SOP: "training 2" },
{ User: "Jon", SOP: "training 1" },
{ User: "Jon", SOP: "training 2" },
{ User: "Ana", SOP: "training 1" },
{ User: "Ana", SOP: "training 2" }
];

var outputdata = [
{ User: "Cesar", SOP: "training 1" },
{ User: "Cesar", SOP: "training 2" },
{ User: "Ana", SOP: "training 1" },
{ User: "Jon", SOP: "training 1" }
];

最终输出数组。

var filtered = [
{ User: "Ana", SOP: "training 2" },
{ User: "Jon", SOP: "training 2" }
];

最佳答案

您可以对项目使用哈希表,然后再排除和过滤记录。

var arrSOPrecords = [{ User: "Cesar", SOP: "training 1" }, { User: "Cesar", SOP: "training 2" }, { User: "Jon", SOP: "training 1" }, { User: "Jon", SOP: "training 2" }, { User: "Ana", SOP: "training 1" }, { User: "Ana", SOP: "training 2" }],
outputdata = [{ User: "Cesar", SOP: "training 1" }, { User: "Cesar", SOP: "training 2" }, { User: "Ana", SOP: "training 1" }, { User: "Jon", SOP: "training 1" }],
filtered,
hash = Object.create(null);

outputdata.forEach(function (a) {
hash[a.User + '|' + a.SOP] = true;
});
filtered = arrSOPrecords.filter(function (a) {
return !hash[a.User + '|' + a.SOP];
});

console.log(filtered);

关于javascript - 使用 jQuery 或 JavaScript 使用另一个数组过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37814161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com