1

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:

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.

user3174311
  • 1,714
  • 5
  • 28
  • 66
  • Does this answer your question? [How to count the number of occurrences of each item in an array?](https://stackoverflow.com/questions/11649255/how-to-count-the-number-of-occurrences-of-each-item-in-an-array) – Yogi Feb 03 '23 at 14:38

3 Answers3

1

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

let r = 
  data.flatMap(i=>JSON.parse(i.answer)).reduce((a,c)=>(a[c]??=0,a[c]++,a),{})

console.log(r)
Andrew Parks
  • 6,358
  • 2
  • 12
  • 27
1

This seems to work:

const data = [
    {
      entry: 1,
      answer: "[\"aaa\",\"bbb\"]"
    },
    {
      entry: 2,
      answer: "[\"ccc\",\"bbb\"]"
    },
    {
      entry: 3,
      answer: "[\"ccc\",\"bbb\"]"
    }
  ]
  
  const result = data.reduce( (c,e) => (JSON.parse(e.answer).forEach(a => c[a] = (c[a] ?? 0) + 1), c), {} );
  console.log(result)

  console.log('sorted', Object.fromEntries(Object.entries(result).sort( (e1, e2) => e1[0].localeCompare(e2[0]))))
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
1

Use JSON.parse().

const countAnswers = (ans) => {
    return ans.reduce(function (obj, v) {
        const answersParsed = JSON.parse(v.answer);
        
        answersParsed.forEach((answer) => {
            obj[answer] = (obj[answer] || 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));
Anton Podolsky
  • 841
  • 2
  • 11