JavaScript: Reduce an array to nested objects

mayank :

So suppose my array looks like this:

let langArr = [
     ["python", "blue"]
    ,["python", "blue"]
    ,["c++", "red"]
    ,["java", "yellow"]
    ,["javascript", "lime"]
    ,["shell", "green"]
    ,["c++", "red"]
];

what I want is something like this:

{
  python: {
    count: 2
    color: "blue"
  }
  c++: {
    count: 2
    color: "red"
  }
  java: {
    count: 1
    color: "yellow"
  }
  and so on...
}

I tried reduce method like this:

let langCount = langArr.reduce((lang, [name, color]) => {
      lang[name] = (lang[name] || 0) + 1;
      lang[color] = 'color';
      return lang;
    }, {});
    console.log(langCount);

but I get this output:

{
  python: 2
  blue: "color"
  c++: 2
  red: "color"
  java: 1
  yellow: "color"
  and so on...
}
Nina Scholz :

You need an object for each language.

This approach takes an object as default value if lang[name] is falsy, like undefined.

The pattern

variable = variable || value;

works with a logical OR ||:

  • if variable has a truthy value, take this value,
  • if variable has a falsy value, take value instead.

let langArr = [["python", "blue"], ["python", "blue"], ["c++", "red"], ["java", "yellow"], ["javascript", "lime"], ["shell", "green"], ["c++", "red"]],
    langCount = langArr.reduce((lang, [name, color]) => {
        lang[name] = lang[name] || { count: 0, color };
        lang[name].count++;
        return lang;
    }, {});

console.log(langCount);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=342066&siteId=1