0

I have to find the most common values in array in JavaScript.

my tried coded

eg arrays

var A = ["a", "c", "a", "b", "d", "e", "f"];
var B = ["a", "c", "a", "c", "d", "e", "f"];

function mode(array)
{
    if(array.length == 0)
        return null;
    var modeMap = {};
    var maxEl = array[0], maxCount = 1;
    for(var i = 0; i < array.length; i++)
    {
        var el = array[i];
        if(modeMap[el] == null)
            modeMap[el] = 1;
        else
            modeMap[el]++;  
        if(modeMap[el] > maxCount)
        {
            maxEl = el;
            maxCount = modeMap[el];
        }
    }
    return maxEl;
}

and other one

var store = ['1','2','2','3','4'];
var frequency = {};  // array of frequency.
var max = 0;  // holds the max frequency.
var result;   // holds the max frequency element.
for(var v in store) {
        frequency[store[v]]=(frequency[store[v]] || 0)+1; // increment frequency.
        if(frequency[store[v]] > max) { // is this frequency > max so far ?
                max = frequency[store[v]];  // update max.
                result = store[v];          // update result.
        }
}

Code works ok in case A, "a" repeat most with 2 times occurrence, so I get "a" that's ok.

but in case of B, "a" & "c" both repeat 2 times but I get only A, but my requirement is to get both "a" & "c".

Dinesh
  • 835
  • 2
  • 17
  • 37
  • 2
    Possible duplicate of [Get the element with the highest occurrence in an array](http://stackoverflow.com/questions/1053843/get-the-element-with-the-highest-occurrence-in-an-array) and [Get the item that appears the most times in an array](http://stackoverflow.com/questions/3783950/get-the-item-that-appears-the-most-times-in-an-array) – Benny Bottema Mar 09 '16 at 11:46
  • Because you are performing a strictly greater than comparsion. You are also returning only maxEl, which corresponds with 1 index. To return more than 1 result, you should return an array – Nadir Mar 09 '16 at 11:46
  • So you can't just store the `maxEl` element.. I suggest you to keep track of maxCount, then in the end just return all the elements with that count – frarugi87 Mar 09 '16 at 11:47
  • Write down in English the steps you need to do. Then, convert the English into JavaScript. –  Mar 09 '16 at 12:03
  • @BennyBottema - Not only is it a duplicate question ... OP's code is identical to the selected answer. So apparently "tried coding" means "copy and pasted". – Yogi Mar 09 '16 at 12:05

2 Answers2

0

After your for loop add the following code

result = [];
for ( var key in frequency )
{
   if (frequency[key] == max)
   {
     result.push(key);
   }
}
console.log(result);

It is iterating the frequency array again to return items with frequency same as max-frequency.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

Collect the items with an Array#reduce().

function getMostCommon(array) {
    var count = {};
    array.forEach(function (a) {
        count[a] = (count[a] || 0) + 1;
    });
    return Object.keys(count).reduce(function (r, k, i) {
        if (!i || count[k] > count[r[0]]) {
            return [k];
        }
        if (count[k] === count[r[0]]) {
            r.push(k);
        }
        return r;
    }, []);
}

var a = ["a", "c", "a", "b", "d", "e", "f"],
    b = ["a", "c", "a", "c", "d", "e", "f"];

document.write('<pre>' + JSON.stringify(getMostCommon(a), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(getMostCommon(b), 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392