Yamoshi Wolverine
Yamoshi Wolverine

Reputation: 549

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!

Upvotes: 2

Views: 4432

Answers (6)

FR STAR
FR STAR

Reputation: 702

Try the following:

var candles = [100,100,200,200,200,300,300,300,400,400,400];

let tempArray = {}

for (let index = 0; index <= (candles.length - 1); index++) {

    let valueToCompare = candles[index];

    if (tempArray[valueToCompare]) {
        tempArray[valueToCompare] = tempArray[valueToCompare] + 1;
    } else {
        tempArray[valueToCompare] = 1;
    }
}

let highestValue;
Object.values(tempArray).forEach(item => {
    

    if (highestValue === undefined) highestValue = item;

    if (highestValue < item) highestValue = item;
});

console.log(highestValue);

Upvotes: 0

Rajib Chy
Rajib Chy

Reputation: 880

Try as following ==>

function getDuplicate( arr ){
    let obj = {}, dup = [];
    for(let i = 0, l = arr.length; i < l; i++){
        let val = arr[i];
        if( obj[val] /**[hasOwnProperty]*/ ) {
            /**[is exists]*/
            if(dup.find(a => a == val) ) continue;
            /**[put Unique One]*/
            dup.push(val);
            continue;
        };
        /**[hold for further use]*/
        obj[val] = true;
    }
    return dup;
};

Use ==>

getDuplicate([100,100,200,200,200,300,300,300,400,400,400]);

Upvotes: 0

HMR
HMR

Reputation: 39360

The following would do the trick assuming that all items in arr are numbers:

//added some numbers assuming numbers are not sorted
var arr = [300,400,200,100,100,200,200,200,300,300,300,400,400,400];

var obj = arr.reduce(//reduce arr to object of: {"100":2,"200":4,"300":4,"400":4}
  (o,key)=>{//key is 100,200, ... o is {"100":numberOfOccurrences,"200":numberOf...}
    o[key] = (o[key])?o[key]+1:1;
    return o;
  },
  {}
);
// obj is now: {"100":2,"200":4,"300":4,"400":4}
//create an array of [{key:100,occurs:2},{key:200,occurs:4}...
var sorted = Object.keys(obj).map(
  key=>({key:parseInt(key),occurs:obj[key]})
)//sort the [{key:100,occurs:2},... by highest occurrences then lowest key
.sort(
  (a,b)=>
    (b.occurs-a.occurs===0)
      ? a.key - b.key
      : b.occurs - a.occurs
);
console.log(
  sorted.filter(//only the highest occurrences
    item=>item.occurs===sorted[0].occurs
  ).map(//only the number; not the occurrences
    item=>item.key
  )
);

Upvotes: 1

brk
brk

Reputation: 50346

Iterating an array using for..in is not a good idea. Check this link for more information.

Hopefully below snippet will be useful

var arr = [100, 100, 200, 200, 200, 300, 300, 300, 400, 400, 400];
//Use a reduce fuction to create an object where 100,200,300 
// will be keys and its value will the number of times it has 
//repeated
var m = arr.reduce(function(i, v) {
  if (i[v] === undefined) {
    i[v] = 1
  } else {
    i[v] = i[v] + 1;
  }
  return i;
}, {});
// Now get the maximum value from that object,
//getMaxRepeated will be 3 in this case

var getMaxRepeated = Math.max(...Object.values(m));
//An array to hold elements which are repeated 'getMaxRepeated' times
var duplicateItems = [];

// now iterate that object and push the keys which are repeated
//getMaxRepeated times
for (var keys in m) {
  if (m[keys] === getMaxRepeated) {
    duplicateItems.push(keys)
  }
}
console.log(duplicateItems)

Upvotes: 1

Venkata Sandeep
Venkata Sandeep

Reputation: 191

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.

Upvotes: 1

atiq1589
atiq1589

Reputation: 2327

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);

Upvotes: 6

Related Questions