2

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!

Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104
Yamoshi Wolverine
  • 401
  • 1
  • 5
  • 12

6 Answers6

6

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);
atiq1589
  • 2,227
  • 1
  • 16
  • 24
1

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.

Venkata Sandeep
  • 191
  • 1
  • 12
  • Don't you think its unnecessary complexity? You make your code difficult to debug. – atiq1589 Apr 03 '18 at 05:46
  • I personally don't feel it difficult in debugging, just creating json object with array value as key, and how many times it appeared in array as json key value, who'd find it difficult to debug ? As I can see, your code also follows the same logic except creating object, thats it. Anyway thanks for your suggestion! :) – Venkata Sandeep Apr 03 '18 at 06:06
  • Your last edit is quit fine. Now its much easier to understand. – atiq1589 Apr 03 '18 at 06:15
1

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)
brk
  • 48,835
  • 10
  • 56
  • 78
1

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
  )
);
HMR
  • 37,593
  • 24
  • 91
  • 160
0

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]);
Rajib Chy
  • 800
  • 10
  • 22
0

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);
FR STAR
  • 662
  • 4
  • 24
  • 50