如果我有两个带有文件的数组
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) );
但这会比较每个整个项目。我只想比较文件名。提供文件的格式需要被 chop ,所以我得到:
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/