Xavier
Xavier

Reputation: 4017

Create and populate array dynamically with javascript

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", ...];

Upvotes: 0

Views: 63

Answers (2)

Hugo Martin
Hugo Martin

Reputation: 167

Something shorter would be nice:

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

Upvotes: 0

wangdev87
wangdev87

Reputation: 8751

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);

Upvotes: 4

Related Questions