-2

I have data sets as repeatable numbers:

02 02 25 27 32 47,
45 55 11 44 65 47,
12 02 56 48 65 25,
45 56 11 44 76 54,

It does not matter it can be an array or an object, but what I need to do is to find the the most frequent value in a column. So, lets say, in my sample data the first column should bring 45, second 02, third 11 and so on.

What could be the easiest approach to find out the most repeatable value in a column. It can be javascript (preferable) or any other backend programming language.

zero323
  • 322,348
  • 103
  • 959
  • 935
funguy
  • 2,072
  • 7
  • 30
  • 41

2 Answers2

0

sort them then find all the neighbor count the same number then sort the count. Counting the occurrences of JavaScript array elements

Community
  • 1
  • 1
Madan Ram
  • 880
  • 1
  • 11
  • 18
0

You can use an object to accumulate counts of values in array and then select the value with biggest count:

function mostFrequentValueOf( arr ) {
    var counts = {};
    for( var i=0; i<arr.length; ++i ) {
        var val = arr[i];
        if( counts[val] )
            counts[val]++;
        else
            counts[val]=1;
    }
    var maxcnt=0, maxval;
    for( var val in counts ) {
        var cnt = counts[val];
        if( cnt > maxcnt ) {
            maxcnt = cnt;
            maxval = val;
        }
    }
    return maxval;
}

By the way, this will work with string array values too.

If your data is organized as array of columns

var columns = [ [02,45,12,45], [02,55,02,56], [25,11,56,11], [27,44,48,44], [32,65,65,76], [47,47,25,54] ];

you can call the function directly: mostFrequentValueOf(columns[0])

If your data is organized as array of rows

var rows = [ [02,02,25,27,32,47], [45,55,11,44,65,47], [12,02,56,48,65,25], [45,56,11,44,76,54] ];

I think you should reorganize the data

var column_idx=0, column=[];
for( var i=0; i<rows.length; ++i )
    column.push( rows[i][column_idx] );

then use the same function mostFrequentValueOf(column)

Here it is in JSfiddle: http://jsfiddle.net/V4TRc

mas.morozov
  • 2,666
  • 1
  • 22
  • 22