Ad

Find Most Frequent Item Of A JS Array With While Loop?

- 1 answer

I have created a function that finds the most frequent item of a JS array with two for loops and displays the item and how many times there is in the array. How can I do it with a while loop?

var arr = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];

//ta = times appeared / m = max / arrchar = array character
var ta = 1;
var m = 0;
var arrchar;

for (var i = 0; i < arr.length; i++) {
  for (var j = i; j < arr.length; j++) {
    if (arr[i] == arr[j])
      m++;
    if (ta < m) {
      ta = m;
      arrchar = arr[i];
    }
  }
  m = 0;
}
console.log(arrchar + "(" + ta + ")");

Ad

Answer

The purpose of having a while loop is to use exit conditions. Since there is no exit condition I've essentially created a fairly efficient for loop algorithm and just replaced the for loop with a while loop.

var arr = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];

var occurences = {};

var max = 0;
var champion;

var index = 0;

while (index < arr.length) {
  var item = arr[index];
  occurences[item] = (occurences[item] || 0) + 1;
  if (occurences[item] > max) {
    max = occurences[item];
    champion = item;
  }
  index += 1;
}

console.log(`${champion} has ${max} occurences`);

Unfortunately the code above will always consider 3 and "3" as the same value. If you do not wish for that to happen then you should use a map instead.

var arr = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];

var occurences = new Map();

var max = 0;
var champion;

var index = 0;

while (index < arr.length) {
  var item = arr[index];
  var newSize = (occurences.get(item) || 0) + 1;
  occurences.set(item, newSize);
  if (newSize > max) {
    max = newSize;
    champion = item;
  }
  index += 1;
}

console.log(`${champion} has ${max} occurences`);

Ad
source: stackoverflow.com
Ad