'Map array of locales and change each locale to language name
Using Next.js, I'm getting the current locale and all available locales for a language selection menu:
const {cl, al} = useContext(LangContext);
// cl = "en-US"
// al = ["en-US", "de-DE"]
I wrote this function to return the full language name:
const clAlias = ()=> {
if (cl === "en-US") { return "English" };
if (cl === "de-DE") { return "Deutsch" };
}
Now I want to map al , but instead of having ["en-US", "de-DE"] I want to have ["English", "Deutsch"]. It not only looks better but also makes it easier for the user to select their language.
What would be the best way to do so?
Solution 1:[1]
How about an object.
const clAlias = {
"en-US": "English",
"de-DE": "Deutsch"
}
//...
al.map(x => clAlias[x])
Solution 2:[2]
You can use Array.from method. It return new array without change al
And don't forget add arguments in clAlias() like clAlias(cl)
const al = ["en-US", "de-DE"];
const clAlias = (cl) => {
if (cl === "en-US") {
return "English";
}
if (cl === "de-DE") {
return "Deutsch";
}
};
const answer = Array.from(al, (e) => clAlias(e));
console.log(answer);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | onivek |
| Solution 2 | GoSSy4691 |
