Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the most duplicate "values" in javascript array?

my question is actually similar to: Extracting the most duplicate value from an array in JavaScript (with jQuery)

I Found this but it always return one value only which is 200.

var arr = [100,100,200,200,200,300,300,300,400,400,400];
    var counts = {}, max = 0, res;
    for (var v in arr) {
      counts[arr[v]] = (counts[arr[v]] || 0) + 1;
      if (counts[arr[v]] > max) { 
        max = counts[arr[v]];
        res = arr[v];
      }

    }
    console.log(res + " occurs " + counts[res] + " times");

pls help me to return values not just one...

The result is should like this: 200,300,400 . pls help thank you!

like image 329
Yamoshi Wolverine Avatar asked Feb 13 '26 18:02

Yamoshi Wolverine


2 Answers

You have to iterate your counts to find the max occurred result.

var arr = [100,100,200,200,200,300,300,300,400,400,400];
    var counts = {}, max = 0, res;
    for (var v in arr) {
      counts[arr[v]] = (counts[arr[v]] || 0) + 1;
      if (counts[arr[v]] > max) { 
        max = counts[arr[v]];
        res = arr[v];
      }

    }
    var results = [];
    for (var k in counts){
      if (counts[k] == max){
        //console.log(k + " occurs " + counts[k] + " times");
        results.push(k);
      }
    }
    console.log(results);
like image 93
atiq1589 Avatar answered Feb 15 '26 06:02

atiq1589


Create a Object iterating the arry containing the indexes of most repeated values, like below

var arr = [100,100,200,200,200,300,300,300,400,400,400];
valObj = {}, max_length = 0, rep_arr = [];

arr.forEach(function(el,i){
   if(valObj.hasOwnProperty(el)){
       valObj[el] += 1;
       max_length = (valObj[el] > max_length) ? valObj[el] : max_length
   }
   else{
       valObj[el] = 1;
   }
});

Object.keys(valObj).forEach(function(val){
    (valObj[val] >= max_length) && (rep_arr.push(val))
});
console.log(rep_arr);

After the object is created with key as array value and value as array indexes of that value, you can play/parse that. Hope this helps.

like image 40
Venkata Sandeep Avatar answered Feb 15 '26 06:02

Venkata Sandeep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!