0

I have an array of programming language like: 

const tags = ["js", "ruby", "ios", "python", "go"];

I also have a list of users like: 

const user = [
  {
    "id": "userId_1",
    "language": ["ruby", "ios"]
  }, 
  ...
];

Is there a nice way to populate an array named by the language name with the Ids of users?

Something like: 

const ruby = ["userId_1", "userId_3", "userId_8", ...];
4
  • The variable name will not translate, you must scope it. Commented Jan 19, 2021 at 14:19
  • he meant id, not variable name. Commented Jan 19, 2021 at 14:21
  • @WilliamWang I meant that the variable name ruby gets erased. You must store it in a scoped name. Commented Jan 19, 2021 at 14:26
  • ah, yes, correct. according to my answer, we should call it by output.ruby, ... Commented Jan 19, 2021 at 14:27

2 Answers 2

4

You can use Array.reduce().

const tags = ["js", "ruby", "ios", "python", "go"];

const user = [
  {
    "id": "userId_1",
    "language": ["ruby", "ios"]
  }, 
  {
    "id": "userId_2",
    "language": ["ruby", "python"]
  }, 
  {
    "id": "userId_3",
    "language": ["go", "ios"]
  }, 
];

const output = user.reduce((acc, cur) => {
  cur.language.forEach(lang => {
    if (!acc[lang]) acc[lang] = [];
    acc[lang].push(cur.id);
  });
  return acc;
}, {});

console.log(output);

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

5 Comments

You don't even need the tags array right?
correct for now, just tags will be needed if you needs all the tags in the output to refactor the output.
Hum, I got something like { '[object Object]': [ 'userId_1', 'userId_2',
can you run the above code snippet ? result says { "ruby": [ "userId_1", "userId_2" ], "ios": [ "userId_1", "userId_3" ], "python": [ "userId_2" ], "go": [ "userId_3" ] }
Yeah, nevermind my "real world code" just had a type issue (basically language is an object! Thanks for your help man!
0

Something shorter would be nice:

const ruby = user.map((user) => user.language.includes("ruby") ? user.id : undefined);

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.