首页 > 解决方案 > 使用 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"
]

通过使用任何链接方法?

标签: javascriptnode.jsarraysfilterreplace

解决方案


您可以在不创建另一个变量的情况下链接过滤后的数组,并使用隐式返回使事情更简洁:

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);


推荐阅读