Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Count objects in array js node

I want to create a new variable that will count all the names and them as a assignments says but I am kind of stuck.

I have an array with names.

names = [Jan, Jan, Jana]

I would like to count these names, which is quite easy but what I am struggling with is putting them as the assignment says below.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const dtoOut = {
 chartData: {
    all: [
     {label: "Jan", value: 2},
     {label: "Jana", value: 1},

any help?

>Solution :

if your keys do not change this is one easy way

const result = {
 chartData: {
   all: names.reduce((acc, curr) => {
     const obj = acc.find(o => o.label === curr);
     if (obj) {
       obj.value += 1;
     } else {
       acc.push({label: curr, value: 1});
     }
     return acc;
   }, [])
 }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading