[英]how to get one string / value from an Array which has the same name but has a different type using JavaScript?
example:例子:
let before = [ "apple.jpg", "apple.png", "apple.svg" , "banana.png", "banana.jpg" ]
what I want:我想要的是:
let after = ["apple.jpg", "banana.png"]
You can create a map which is having file names as keys and files with the same name as values您可以创建一个 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];
});
After this step you will get an object (fileMap) like this在这一步之后,你会得到一个像这样的 object (fileMap)
{
apple: ["apple.jpg", "apple.png", "apple.svg"]
banana: ["banana.png", "banana.jpg"]
}
Then you can iterate over this object and get the desired result然后你可以遍历这个 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"]
Another example with reduce
, concat
, split
and some
:另一个使用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);
You can also make use of Array.filter
by taking closure of Set
, Here is working example:您还可以通过关闭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.