Debug School

rakesh kumar
rakesh kumar

Posted on

How to count which word occurrence is highest in objects of array

Requirement
my requirement which word occurance like answerone or answertwo or answerthree in checkonefield is highest in array of objects

Image description

const wordCounts = {
  answerone: 0,
  answertwo: 0,
  answerthree: 0,
  answerfour: 0
};

data[0].checkone.forEach(item => {
  if (item === 'answerone') {
    wordCounts.answerone++;
  } else if (item === 'answertwo') {
    wordCounts.answertwo++;
  } else if (item === 'answerthree') {
    wordCounts.answerthree++;
  } else if (item === 'answerfour') {
    wordCounts.answerfour++;
  }
});

let highestWord = '';
let highestCount = 0;

for (const word in wordCounts) {
  if (wordCounts[word] > highestCount) {
    highestWord = word;
    highestCount = wordCounts[word];
  }
}

console.log('Highest word:', highestWord);
console.log('Highest count:', highestCount);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)