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

How to count the occurrences of the values of an array in a array of objects

I have an array of objects like this

[
  {
    entry: 1,
    answer: "[\"aaa\",\"bbb\"]"
  },
  {
    entry: 2,
    answer: "[\"ccc\",\"bbb\"]"
  },
  {
    entry: 3,
    answer: "[\"ccc\",\"bbb\"]"
  }
]

Note that the value in answer is a stringified array. I would like to count how many occourrence of each answer and get back an object like

{
  "aaa": 1,
  "ccc": 2,
  "bbb": 3,
}

what I tried so far:

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 countAnswers = (ans) => {
    return ans.reduce(function (obj, v) {
        obj[v.answer] = (obj[v.answer] || 0) + 1;
        return obj;
    }, {});
};

this function counts any occourrence of the stringified answer but I don’t understand how to revert the stringify array and count the elements within it.

>Solution :

Use JSON.parse().

const countAnswers = (ans) => {
    return ans.reduce(function (obj, v) {
        const answersParsed = JSON.parse(v.answer);
        
        answersParsed.forEach((answer) => {
            obj = (obj || 0) + 1;
        });
        
        return obj;
    }, {});
};

const answers = [
  {
    entry: 1,
    answer: "[\"aaa\",\"bbb\"]"
  },
  {
    entry: 2,
    answer: "[\"ccc\",\"bbb\"]"
  },
  {
    entry: 3,
    answer: "[\"ccc\",\"bbb\"]"
  }
];

console.log(countAnswers(answers));
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