My goal is to organize a list of server names into a map using a specific logic.
For instance, with names like:
"temp-a-name1", "temp-a-name2", "temp-b-name1", "temp-b-name2"
They would be mapped as:
{
a: [
"temp-a-name1",
"temp-a-name2"
],
b: [
"temp-b-name1",
"temp-b-name2"
]
}
The key will always be the first letter after the dash "-".
Although my JavaScript knowledge is limited, I have achieved this by taking a simple approach. However, I am curious if there is a more efficient and typical JavaScript way to accomplish this task.
const servers = ["temp-a-name1", "temp-a-name2", "temp-b-name1", "temp-b-name2"];
let map = {};
let key;
for (const server of servers) {
key = server.charAt(server.indexOf("-") + 1);
if (key in map) {
map[key].push(server);
} else {
map[key] = [server];
}
}