0

I'm using this algorithm to find the most common string in an array the only problem is when an array contains two elements or equals amounts of strings the following method does not work exp: (arr["Test","Test2"]) returns nothing

Arr["Test", "Test", "Test","Test2"]
//Should return "Test"

  _correctName(array) {
 const modeMap = {};

let maxElement = "";
let maxCount = 1;

for (let i = 0; i < array.length; i++) {
  const element = array[i];
  if (modeMap[element] == null)
    modeMap[element] = 1;
  else
    modeMap[element]++;
  if (modeMap[element] > maxCount) {
    maxElement = element;
    maxCount = modeMap[element];
  }
}
 return maxElement;
};
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
J.lan
  • 223
  • 4
  • 17

1 Answers1

1

The problem is that you started maxCount with 1.

If each element in your array appears only once, then none of them will overpass the initial 1 value.

Try again with maxCount starting with 0.

Pedro Lima
  • 1,576
  • 12
  • 21