0

I'm trying to store some server names in a map based on some predefined logic.

For example if the names are:

"temp-a-name1", "temp-a-name2", "temp-b-name1", "temp-b-name2"

They'll be stored in a map as:

{
  a: [
    "temp-a-name1",
    "temp-a-name2"
  ],
  b: [
    "temp-b-name1",
    "temp-b-name2"
  ]
}

The first letter between the two "-" will always be the key

I'm not too familiar with javascript so I've done this the naive way but I was wondering if there's a better, more javascripty way to do this.

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];
  }
}
1
  • 1
    Stick with your version. IMO code is readable and easy to understand, so there is no need for refactoring. BTW, such questions are better suitable for codereview.stackexchange.com. Commented Sep 13, 2019 at 21:55

4 Answers 4

3

You could use the reduce() function:

let servers = ["temp-a-name1", "temp-a-name2", "temp-b-name1", "temp-b-name2"];

let map = servers.reduce((acc, server) => {
  let key = server.charAt(server.indexOf("-") + 1);

  if (acc[key])
    acc[key].push(server);
  else
    acc[key] = [server];
    
  return acc;
}, {})

console.log(map)

Sign up to request clarification or add additional context in comments.

1 Comment

reduce() is not an ES6 feature
1

Try this:

const servers = ["temp-a-name1", "temp-a-name2", "temp-b-name1", "temp-b-name2"];
const result = servers.reduce((acc, cur) => ({
    ...acc,
  [cur.split('-')[1]]: (acc[cur.split('-')[1]] || []).concat([cur]),
}), {})
console.log(result);

I think this counts as "javascripty"

Comments

1

I would use reduce. A naive way of getting the key could be .split('-')[1].

const names = ['temp-a-name1', 'temp-a-name2', 'temp-b-name1', 'temp-b-name2'];
const map = names.reduce((map, name) => {
  const key = name.split('-')[1];
  const namesWithKey = map[key] || [];

  return { ...map, [key]: [...namesWithKey, name] };
}, {});

console.log(map);

Comments

1

You can also use the new Map data structure something like this:

const servers = ["temp-a-name1", "temp-a-name2", "temp-b-name1", "temp-b-name2"];

const map = new Map();

servers.forEach(item => {
  const key = item.split('-')[1];
  const value = map.get(key) || [];
  value.push(item);
  
  map.set(key, value);
});

// CONSOLE LOG
for (var [key, value] of map.entries()) {
  console.log(key + ' = ' + value);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.