![](/img/trans.png)
[英]How to new a Class by it's string type name and apply a array parameter inside which has null value?
[英]how to get one string / value from an Array which has the same name but has a different type using JavaScript?
例子:
let before = [ "apple.jpg", "apple.png", "apple.svg" , "banana.png", "banana.jpg" ]
我想要的是:
let after = ["apple.jpg", "banana.png"]
您可以創建一個 map,它的文件名作為鍵,文件與值同名
let before = [ "apple.jpg", "apple.png", "apple.svg" , "banana.png", "banana.jpg" ]
const fileMap = {};
before.forEach(file => {
const fileName = file.split('.')[0];
if (fileMap[fileName]) fileMap[fileName].push(file);
else fileMap[fileName] = [file];
});
在這一步之后,你會得到一個像這樣的 object (fileMap)
{
apple: ["apple.jpg", "apple.png", "apple.svg"]
banana: ["banana.png", "banana.jpg"]
}
然后你可以遍歷這個 object 並得到想要的結果
const result = [];
Object.keys(fileMap).forEach(key => {
if (fileMap[key].length > 1)
result.push(fileMap[key][0]);
});
console.log(result); // ["apple.jpg", "banana.png"]
另一個使用reduce
、 concat
、 split
和some
的例子:
const before = ["apple.jpg", "apple.png", "apple.svg", "banana.png", "banana.jpg"] const after = before.reduce((res, str) => { return res.concat( // If some element in the result array already matches the current one, don't add it res.some(x => x.split('.')[0] === str.split('.')[0])? []: [str] ) }, []); console.log(after);
您還可以通過關閉Set
來使用Array.filter
,這是工作示例:
var before = [ "apple.jpg", "apple.png", "apple.svg", "banana.png", "banana.jpg" ]; var after = before.filter((s=>(elem)=>(frt=elem.split('.')[0], .s.has(frt) && s;add(frt)))(new Set)). console;log(after);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.