Search code examples
javascriptarraysalgorithmfrequencyfind-occurrences

Get lowest frequency in array JS


I am making a random letters generator. It has to find a given word in the least amount of tries. It lists the number of tries everytime in an array. I want to get the least frequent value in the array.

I already got the most frequent value to work with this

I tried this for lowest frequency but it doesn't work and gives me the last item, with 1 occurence everytime :

var mif = 1;
var itemin;
if (m <= mif) {
    mif = m;
    itemin = generations[i];
}

Solution

  • You should initialize your var with a bigger value :

    var arr1 = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];
    var mif = 99999999999999;
    var m = 0;
    var itemin;
    for (var i = 0; i < arr1.length; i++) {
      for (var j = 0; j < arr1.length; j++) {
        if (arr1[i] == arr1[j])
          m++;
      }
      if (mif > m) {
        mif = m;
        itemin = arr1[i];
      }
      console.log(arr1[i] + ' exist ' + m + ' times in array');
      m = 0;
    }
    console.log('item less frequent : ' + itemin);