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...
}
Andreas
21.9k7 gold badges52 silver badges58 bronze badges
2 Answers 2
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
variablehas a truthy value, take this value, - if
variablehas a falsy value, takevalueinstead.
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);
answered Mar 9, 2020 at 15:33
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Andreas
This is just another "group by" answer (with the little twist, that it's not an array with all options but a number for the count). This is now already enough for a new answer instead of a dupe-vote?
m00
Thank you so much! can you also please explain what this line does
lang[name] = lang[name] || { count: 0, color };You can use this:
array.reduce((acc, current) => {
if(!acc.hasOwnProperty(current[0])){
acc[current[0]] = {count: 0, color: current[1]};
}
acc[current[0]].count += 1;
return acc;
}, {});
Comments
Explore related questions
See similar questions with these tags.
lang-js
.reduce()snippet so it produces the output you're expecting?countnever occurs in your code, which should make the primary issue obvious - if you had a place to put that, you'd (probably) have the desired structure.