skip to Main Content

Given an array of numbers, I have to find the number with the highest frequency and return it. If there are two or more numbers with the same highest frequency then I need to return the biggest number.

Below is the code I’ve written..

const numbers = [1, 2, 3, 4, 5, 4, 3, 4, 3, 2, 1, 6, 7, 5];
const numArr = [12, 20, 5, 4, 10, 10, 10, 5, 4, 5, 3, 2];

function frequency(array) {
    let object = {}
    let maxCount = 0;
    let result = 0;

    for (let num of array) {
        if (object.hasOwnProperty(num)) {
            object[num] = object[num] + 1;
        }
        else object[num] = 1;
    }
    console.log(object)
    let entry = Object.entries(object)
    for (const [key, val] of entry) {
        if (maxCount < val) {
            maxCount = val;
            result = key;
        }
    }

    for (const [key, val] of entry) {
        result = maxCount === val && key > result ? key : result;

    }
    return [result, maxCount];
}

const [res, count] = frequency(numArr);
console.log(`number with highest freq: ${res}nfrequency: ${count}`)

Function frequency is working with arrays containing single-digit numbers (e.g numbers). But it’s not giving correct output with arrays containing double-digit numbers (e.g numArr)

The above code should output 10 as the number with highest frequency and 3 as its frequency. But it outputs 5 and 3 respectively. Why is that? Is this related to ASCII values? Thankyou for your time.

3

Answers


  1. The keys are already sorted, and if you want the highest "result", you need to change maxCount < val to maxCount <= val, where a higher key will replace a lower key when the frequencies are the same.

    Also, you don’t need the last loop. It does nothing but messing up your code.

    const numbers = [1, 2, 3, 4, 5, 4, 3, 4, 3, 2, 1, 6, 7, 5];
    const numArr = [12, 20, 5, 4, 10, 10, 10, 5, 4, 5, 3, 2];
    
    function frequency(array) {
        let object = {}
        let maxCount = 0;
        let result = 0;
    
        for (let num of array) {
            if (object.hasOwnProperty(num)) {
                object[num] = object[num] + 1;
            }
            else object[num] = 1;
        }
        console.log(object)
        let entry = Object.entries(object)
        for (const [key, val] of entry) {
            // if (maxCount < val) {
            if (maxCount <= val) {
                maxCount = val;
                result = key;
            }
        }
    
        /*
        for (const [key, val] of entry) {
            result = maxCount === val && key > result ? key : result;
    
        }*/
        return [result, maxCount];
    }
    
    const [res, count] = frequency(numArr);
    console.log(`number with highest freq: ${res}nfrequency: ${count}`)

    Finally, you should be able to solve this problem using only one loop.

    const numbers = [1, 2, 3, 4, 5, 4, 3, 4, 3, 2, 1, 6, 7, 5];
    const numArr = [12, 20, 5, 4, 10, 10, 10, 5, 4, 5, 3, 2];
    
    function frequency(array) {
        let object = {};
        let hasHigherFrequency = false, hasEqualFrequencyButHigherValue = false;
        let highestFrequency = {
          res: 0,
          count: 0
        };
    
        for (let num of array) {
            if (object.hasOwnProperty(num)) {
                object[num] = object[num] + 1;
            }
            else object[num] = 1;
            
            hasHigherFrequency = object[num] > highestFrequency.count;
            hasEqualFrequencyButHigherValue = object[num] == highestFrequency.count && num > highestFrequency.res;
            
            if (hasHigherFrequency || hasEqualFrequencyButHigherValue) {
              highestFrequency = {res: num, count: object[num]};
            }
        }
        
        console.log(object);
    
        return highestFrequency;
    }
    
    const {res, count} = frequency(numArr);
    console.log(`number with highest freq: ${res}nfrequency: ${count}`)
    Login or Signup to reply.
  2. Keys in objects are always strings or symbols, never numbers. For most of your code, that’s fine, but it’s a problem in your two for-of loops over Object.entries, since key there will be a string, and you end up setting result to a string. In the second loop, the key > result is a string comparison, which compares digit-by-digit, not numerically.

    Instead of using an object for your counts, use a Map. Map keys can be actual numbers. See MDN’s article on Map for guidelines for when to use objects vs. maps.

    const numbers = [1, 2, 3, 4, 5, 4, 3, 4, 3, 2, 1, 6, 7, 5];
    const numArr = [12, 20, 5, 4, 10, 10, 10, 5, 4, 5, 3, 2];
    
    function frequency(array) {
        let map = new Map();
        let maxCount = 0;
        let result = 0;
    
        for (let num of array) {
            const value = map.get(num) ?? 0;
            map.set(num, value + 1);
        }
        console.log([...map]);
        for (const [key, val] of map) {
            if (maxCount < val) {
                maxCount = val;
                result = key;
            }
        }
    
        for (const [key, val] of map) {
            result = maxCount === val && key > result ? key : result;
        }
        return [result, maxCount];
    }
    
    const [res, count] = frequency(numArr);
    console.log(`number with highest freq: ${res}nfrequency: ${count}`);
    Login or Signup to reply.
  3. You need only 1 loop here, just compare with the max while collecting the counts. That way you also don’t need to care about number/string conversion for the result:

    const numArr = [12, 20, 5, 4, 10, 10, 10, 5, 4, 5, 3, 2];
    
    function frequency(array) {
        const object = {};
        let maxCount = 0, result = 0;
    
        for (const num of array) {
            const val = object[num] = (object[num] ?? 0) + 1;
            if (maxCount < val) maxCount = val, result = num;
            else if (maxCount === val && result < num) result = num;
        }
        return [result, maxCount];
    }
    
    const [res, count] = frequency(numArr.sort().reverse());
    console.log(`number with highest freq: ${res}nfrequency: ${count}`)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search