如何使用文件名数组筛选文件路径数组
How to filter array of file paths using array of file names
使用lodash,如何使用文件名数组过滤出文件路径数组?
var imageNames = ['/Users/x/edm/images/advertiser.jpg', '/Users/x/edm/images/advertiser_mob.jpg', '/Users/x/edm/images/app_store_button.jpg', '/Users/x/edm/images/header.jpg'];
var usedImageNames = ['app_store_button.jpg', 'advertiser.jpg'];
_.mixin({
findArrayItemsUsingArray: function (collection, values) {
return _.filter(collection, function (fileName) {
_.each(values, function (imageName) {
if (_.endsWith(fileName, imageName))
return true;
});
})
}
})
console.log(_.findArrayItemsUsingArray(imageNames, usedImageNames));
假设POSIX文件路径(用/
分隔):
在ES6:中
imageNames.filter(path => {
let parts = path.split('/')
let file = parts[parts.length -1]
return usedImageNames.indexOf(file) !== -1
})
在ES5:中
imageNames.filter(function (path) {
var parts = path.split('/')
var file = parts[parts.length -1]
return usedImageNames.indexOf(file) !== -1
})
在Lodash:
_.filter(imageNames, function (path) {
return _.includes(usedImageNames, _(path).split('/').last())
})
在Lodash+ES6:中
imageNames.filter(path => _.includes(usedImageNames, _(path).split('/').last()))
可以与_.endsWith()
进行比较,但请考虑如果imageNames
阵列中有/path/to/somefilename.jpg
和/path/to/filename.jpg
,而usedImageNames
阵列中只有filename.jpg
,会发生什么情况。
类似地,您也可以使用类似.endsWith('/' + name)
的方法,但为了清晰起见,我更喜欢拆分和最后一个方法。
我做了一些性能测试。结论:不要使用Lodash;)这个带有regexp的版本有时会稍微快一点,但它缺乏清晰度可能不值得:
imageNames.filter(function(path) {
return usedImageNames.indexOf(path.match(/'/([^/]+)$/)[1]) !== -1
})
var objArray = imageNames.map(function(path) {
var splitted = path.split("/");
return {name: splitted[splitted.length - 1],
path: path};
});
_.sort(objArray, "name");
相关文章:
- Javascript-如何读取json文件中的列并将其保存在Javascript数组中
- 正在尝试将JSON文件放入JS数组
- React.js如何从js文件中获取数组
- 将大数组(字符串和类型数组的混合物)存储到blob或文件中/从blob或文件检索大数组的最佳方式
- JavaScript代码,用于在浏览器中显示字节数组中的PDF文件(非base64编码)
- 如何从txt文件中获取要在javascript数组中使用的对象
- 数组在手动写入时有效,但从文本文件加载时无效
- 在将csv文件中的数据分配给数组变量时增强了d3代码
- 将javascript数组写入文件
- 从不一致的文件路径数组中获取键的值
- 如何将json文件中的数据提取到对象数组中,并在两个控制器之间共享
- 读取外部local.txt文件以将数据加载到数组中
- 将文本文件读入数组
- Grunt 可以直接从文件对象/数组或 glob 中的“src”值通过 HTTP 加载远程文件
- 将 FormData 对象放入数组中以从不同的输入文件上载文件
- 验证数组文件字段的表单提交
- 放在哪里;很多“;数据的数组/文件/其他地方,在node.JS上的JS中
- Html5文件读取器-读取本地Json数组文件并仅显示特定部分
- 未由使用 JavaScript 的 JSON 数组文件定义
- 使用JavaScript将JSON数组文件转换为图形