Home > front end >  Get the items that occur the most number of times in an javascript array
Get the items that occur the most number of times in an javascript array

Time:06-29

Lets say i have an array a = [25, 2,3,57,38,41]

What i want to find is the digits that occur the most number of times for example,

For array a the output will be [2, 3, 5] because 2, 3 and 5 each appear 2 times in the array.

CodePudding user response:

You can try something like this:

let freqs = [25, 2,3,57,38,41].map(n => n.toString().split("")).flat().reduce((acc, digit) => {
    if (!acc[digit]) {
        acc[digit] = 0
    }

    acc[digit]   ;

    if (acc[digit] > acc.max) {
        acc.max = acc[digit]
    }

    return acc;
}, {max: 0})

let max = freqs.max

delete freqs.max

Object.entries(freqs).filter(entry => entry[1] === max).map(entry => entry[0])

What does this do:

  1. we're splitting the numbers to digits using n.toString().split("")
  2. then we create one array with all the digits by using flat
  3. we then compute the character frequencies with a reduce
  4. finally we filter only the digits that have the max freq

CodePudding user response:

You could count and build an array of max count items.

const
    array = [25, 2, 3, 57, 38, 41],
    result = Array
        .from(array.join('')).reduce((r, d) => {
            r[d] = (r[d] || 0)   1;
            (r[-r[d]] ??= []).push( d);
            if (r.max < r[d]) {
                r.max = r[d];
                r.result = r[-r[d]];
            }
            return r;
        }, { max: 0 })
        .result;

console.log(result);

  • Related