Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
Find and Calculate Mode in Javascript

I am having some difficulity in how to actually get mode and count for the biggest value of the map. I can't get to count for mode because it show for multiplication 2, what i think happens in my code, is the matter of the loop. Thanks in advance.

var data1 = [1, 1, 1, 2, 2, 4, 1, 1]
function getMode (arr) {
    var obj = {};
    var max = 0;
    let result = []


    arr.forEach(element => {
        if (!obj[element]) obj[element] = 0
        obj[element]++
    });
    if (Object.keys(obj).length === result.length) {
        result = []
    }

    for (let i = 0; i < arr.length; i++) {
        obj[arr[i]] = (obj[arr[i]] + 1) || 1;
    }
    for (var key in obj) {
        if (obj[key] > max) {
            result = [key]
            max = obj[key]
        } else if (obj[key] === max) {
            result.push(key)
        }
    }
    return ("most number value " + result + " with " + max)
}

console.log(getMode(data1));
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!