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!

3
  • So you want to have all values that are tied for the highest duplicate count (if there is a tie), is that it? Commented Apr 3, 2018 at 5:25
  • yes sir pls help Commented Apr 3, 2018 at 5:27
  • the result is in array like this: [200,300,400] Commented Apr 3, 2018 at 5:33

6 Answers 6

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

Sign up to request clarification or add additional context in comments.

2 Comments

sir could you passed the result in array like this [200,300,400]
@PauloDelaCruz see now. Is that your requirements?
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.

3 Comments

Don't you think its unnecessary complexity? You make your code difficult to debug.
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! :)
Your last edit is quit fine. Now its much easier to understand.
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)

Comments

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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.