javascript - 使用 JavaScript / node js 在一种条件下替换和过滤方法
问题描述
我有一个看起来像这样的数组
["home/work/abc.jpg",
"home/work/fish.pdf",
"home/work/fish.jpg",
"home/work/doc/animal.jpg",
"home/work/doc/animal.pdf"];
所以我想过滤包含“.jpg”扩展文件的数组,所以我通过使用过滤掉它
array= array.filter((data)=>{
return data.indexOf(".jpg")>=0
});
所以我得到了我的期望值
[ "home/work/abc.jpg",
"home/work/fish.jpg",
"home/work/doc/animal.jpg"
]
我使用地图功能替换“家/工作/”
let rep="home/work/";
array = array.map((data)=>{
data.replace(rep,"")
});
并得到我的价值
[ "abc.jpg",
"fish.jpg",
"doc/animal.jpg"
]
但问题是我必须使用两种方法来过滤和替换它们有没有可能我可以合并这两种方法并最小化我的代码
array= array.filter((data)=>{
return data.indexOf(".jpg")>=0
});
let rep="home/work/";
array = array.map((data)=>{
data.replace(rep,"")
});
预期产出
[ "abc.jpg",
"fish.jpg",
"doc/animal.jpg"
]
通过使用任何链接方法?
解决方案
您可以在不创建另一个变量的情况下链接过滤后的数组,并使用隐式返回使事情更简洁:
const filenames = ["home/work/abc.jpg",
"home/work/fish.pdf",
"home/work/fish.jpg",
"home/work/doc/animal.jpg",
"home/work/doc/animal.pdf"];
const rep="home/work/";
const result = filenames
.filter(file => file.includes('.jpg'))
.map(file => file.replace(rep, ''));
console.log(result);
要在单次迭代中实际完成,您必须放弃链接,并使用reduce
标准迭代方法。
const filenames = ["home/work/abc.jpg",
"home/work/fish.pdf",
"home/work/fish.jpg",
"home/work/doc/animal.jpg",
"home/work/doc/animal.pdf"];
const rep="home/work/";
const result = [];
for (const file of filenames) {
if (file.includes('.jpg')) result.push(file.replace(rep, ''));
}
console.log(result);
推荐阅读
- javascript - Javascript 和 jQuery 都停止在 for 循环中删除选项
- php - 在 Bootstrap 日期选择器中禁用过去的日期
- elasticsearch - 需要通过 URI 示例进行 Elasticsearch 多索引搜索
- python - 出现以下错误迁移 Django App。有人有答案吗?
- r - 我无法在 R3.0.2 中安装 stan
- bash - 将 curl 与 Windows 路径一起使用
- javascript - 通过 Javascript / Jquery 更改 JSColor 值
- jenkins - WinRM 连接问题
- ios - 使用strokeColor,从中心到圆周画一条线
- python - 熊猫数据重新排列