我想从arr_2中删除包含arr_1域名的那些项目
let arr_1 = ["domain1.com", "domain2.com"];
let arr_2 = [
"domain1.com/about-us",
"domain3.com/contact-us",
"domain4.com/privacy-policy",
"domain2.com/pricing-plans",
"sub.domain2.com/home-1",
];
let filtered_arr = [];
arr_2.forEach((item) => {
if (item.indexOf(arr_1) == -1) {
filtered_arr.push(item);
}
});
console.log(filtered_arr);
我想要这段代码的结果["domain3.com/contact-us", "domain4.com/privacy-policy"],但是它打印了整个arr_2
发布于 2022-05-06 06:33:18
不能对字符串调用indexOf并将数组作为参数传递。
您应该使用find来检查item是否有来自arr_1的域。
而且使用filter的代码比forEach要干净得多。
let arr_1 = ["domain1.com", "domain2.com"];
let arr_2 = [
"domain1.com/about-us",
"domain3.com/contact-us",
"domain4.com/privacy-policy",
"domain2.com/pricing-plans",
"sub.domain2.com/home-1",
];
let filtered_arr = arr_2.filter(item => {
return !arr_1.find(domain => item.includes(domain));
});
console.log(filtered_arr);
注意:也会过滤掉"example.com/domain1.com“。
发布于 2022-05-06 06:28:32
您的代码现在正在返回整个arr_2,因为您的筛选逻辑不检查arr_2的每一项是否包含arr_1中的一个匹配字符串。
indexOf(arr_1)本质上是在arr_2中搜索整个arr_1数组中的每个项。函数将始终返回-1,因为arr_2的每一项都是字符串,永远不会与整个arr_1数组匹配。
我假设您也希望查看arr_1中的每一项,因此您可能应该在forEach循环中为arr_2执行arr_1.forEach((item1) => { }),并在这个内环中执行indexOf检查。
发布于 2022-05-06 06:53:02
您可以使用filter some和includes实现它。
let arr_1 = ["domain1.com", "domain2.com"];
let arr_2 = [
"domain1.com/about-us",
"domain3.com/contact-us",
"domain4.com/privacy-policy",
"domain2.com/pricing-plans",
"sub.domain2.com/home-1",
];
const arr3 = arr_2.filter(url => !arr_1.some(domain => url.includes(domain)))
console.log(arr3)
https://stackoverflow.com/questions/72136879
复制相似问题