-2

So I have this object like this

{
"value": ["aaa", "bbb", "ccc", "aaa"], 
"answer": ["lorem", "lorem", "lorem", "lorem"], 
"question": ["lorem", "lorem", "lorem", "lorem"]}
}

How to get word count from property value?

I tried using reduce()

const countedNames = query.reduce((allNames: any, name: any) => {
      const currCount = allNames[name.value] ?? 0;
      return {
        ...allNames.value,
        [name.value]: currCount + 1,
      };
    }, {});

but I didn't get the result I'm expecting

The result I'm expecting is something like this

{
"aaa": 2,
"bbb": 1,
"ccc": 1
}
Yasamura
  • 41
  • 3
  • What is `query`? Your input is an object and you should get an error when you use `.reduce` – adiga Dec 09 '22 at 08:10
  • duplication: https://stackoverflow.com/questions/19395257/how-to-count-duplicate-value-in-an-array-in-javascript – rszf Dec 09 '22 at 08:11
  • or here: https://stackoverflow.com/questions/12749200/how-to-count-array-elements-by-each-element-in-javascript – rszf Dec 09 '22 at 08:11
  • @adiga Seems this problem has been asked a million times,LOL – flyingfox Dec 09 '22 at 08:35

1 Answers1

-1

reduce should be used on your array query.value directly and not on the parent object

const query = {
  "value": ["aaa", "bbb", "ccc", "aaa"],
  "answer": ["lorem", "lorem", "lorem", "lorem"],
  "question": ["lorem", "lorem", "lorem", "lorem"]
}

const countedNames = query.value.reduce((allNames, name) => {
  const currCount = allNames[name] ?? 0;
  return {
    ...allNames,
    [name]: currCount + 1,
  };
}, {});

console.log(countedNames);
Weedoze
  • 13,683
  • 1
  • 33
  • 63