Home > Back-end >  How can I get top five elements that appears the most in the array?
How can I get top five elements that appears the most in the array?

Time:10-08

I already know how to get a element that appears the most in array but now I have a case where I need to get top 5 elements that appears most in the array.

I have this array:

[
  "fuji",
  "acros",
  "bombshell",
  "4za",
  "aerozine",
  "bianchi-milano",
  "bianchi-milano",
  "aerozine",
  "rapha",
  "rapha",
  "rapha",
  "100%",
  "100%",
  "100%",
  "100%"
];

So top five should be:

[
  "100%",
  "rapha",
  "bianchi-milano",
  "aerozine",
  "fuji" // This one can be random as all the rest appears only once
]

And this is the code that I have for finding one that is duplicating the most:

array.sort( (a, b) => arr.filter(v => v === a).length - arr.filter(v => v === b).length ) .pop();

Any help but also a clarification would mean a lot! Thanks!!

CodePudding user response:

You need frequency of all words first and then get top 5 frequent ones (easier if you sort them first and then get top 5)


let a = [
  "fuji",
  "acros",
  "bombshell",
  "4za",
  "aerozine",
  "bianchi-milano",
  "bianchi-milano",
  "aerozine",
  "rapha",
  "rapha",
  "rapha",
  "100%",
  "100%",
  "100%",
  "100%"
];

let hashMap = {}
a.map(e=>{
   if(hashMap[e]) hashMap[e]  ;
   else           hashMap[e]=1
})

let keys = Object.keys(hashMap);
let values = Object.values(hashMap);
let array = keys.map((e,i)=>({name:keys[i],value:values[i]}))
array.sort(function (a, b) {
  return a.value - b.value;
});
array.splice(-5);

CodePudding user response:

const myArray = [
    'fuji',
    'acros',
    'bombshell',
    '4za',
    'aerozine',
    'bianchi-milano',
    'bianchi-milano',
    'aerozine',
    'rapha',
    'rapha',
    'rapha',
    '100%',
    '100%',
    '100%',
    '100%'
]
const sortByFrequency = (array) => {
    var frequency = {}

    array.forEach(function (value) { frequency[value] = 0 })

    var uniques = array.filter(function (value) {
        return   frequency[value] == 1
    })

    return uniques.sort(function (a, b) {
        const y = frequency[b] - frequency[a]
        return y
    })
}

And then call this function:

sortByFrequency(myArray).slice(0, 5)

CodePudding user response:

const items = [
  "fuji",
  "acros",
  "bombshell",
  "4za",
  "aerozine",
  "bianchi-milano",
  "bianchi-milano",
  "aerozine",
  "rapha",
  "rapha",
  "rapha",
  "100%",
  "100%",
  "100%",
  "100%"
];

const totals = items.reduce((acc, item) => ({
  ...acc,
  [item]: acc[item] ? acc[item]   1 : 1
}), {});

const totalsDesc = Object.keys(totals).sort(
  (item1,item2) => totals[item1] > totals[item2] ? -1 : 1
);

const result = totalsDesc.slice(0,5);

console.log(result);

CodePudding user response:

See below

const list = ['j', 'b', 'c', 'tt', 'z', 'b', 'c', 'a', 'tt', 'tt'];

function Counter(array) {
  array.forEach(val => this[val] = (this[val] || 0)   1);
}

console.log(new Counter(list));
  • Related