gpt4 book ai didi

javascript - 如何将一个数组项的一部分与第二个数组中的一部分数组项进行比较?

转载 作者:行者123 更新时间:2023-12-01 15:53:56 25 4
gpt4 key购买 nike

如果我有两个带有文件的数组

arr1 = ['file1.webp', 'file2.webp', ...];
arr2 = ['file1.jpg', 'file2.png', 'file3.jpg', 'file4.jpg', ...];

我如何检查哪些数组项相等,减去 *.format部分?

这个想法是,如果有两个相等的项目,则可以使用 webp和替代源。如果项目不匹配,则不提供 webp源。两种情况都会在以后导致不同的图像处理。

我可以像这样比较两个数组中的项目: let match = arr1.find( val => arr2.includes(val) );
但这会比较每个项目。我只想比较文件名。提供文件的格式需要被截断,所以我得到:
arr1 = ['file1', 'file2', ...];
arr2 = ['file1', 'file2', 'file3', 'file4', ...];

然后,我可以过滤掉两个数组之间的所有匹配项。我一直在寻找一个真正的解决方案,但是我仍然不确定如何到达那里。

最佳答案

使用修剪文件扩展名的功能,您可以构造一个其中一个转换数组的Set。然后遍历另一个数组,并检查其变换后的项是否在Set中:

const arr1 = ['file1.webp', 'file2.webp'];
const arr2 = ['file1.jpg', 'file2.png', 'file3.jpg', 'file4.jpg'];

const transform = str => str.replace(/\.[^.]+$/, '');
const set1 = new Set(arr1.map(transform));
for (const item of arr2) {
if (set1.has(transform(item))) {
console.log('Match for', item);
} else {
console.log('No match for', item);
}
}

关于javascript - 如何将一个数组项的一部分与第二个数组中的一部分数组项进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60691212/

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