ocomfd
ocomfd

Reputation: 4020

How to sort an array, which most common element at first?

for example, suppose I have an array : [3,2,2,1,4,5,3,2,2,1,1], which I want to sort into this form:

[2,2,2,2,1,1,1,3,3,4,5]

which 2 is the most common element, then 1 and so on,how can I write a sort function:

let arr=[3,2,2,1,4,5,3,2,2,1,1];
arr.sort(function(p0,p1){
  //how to write it?
});

to do that?

I tried:

 let arr=[3,2,2,1,4,5,3,2,2,1,1];
 let numPosMap=new Map();
 for(let i=0;i<arr.length;i++){
     let num=arr[i];
     if(!numPosMap[num]){
         numPosMap[num]=[];
     }
     numPosMap[num].push(i);
 }
 let posArrayArray=[];
 for(let num in numPosMap) {
     posArrayArray.push(numPosMap[num]);
 }
 posArrayArray.sort(function(a,b){
   return a.length<b.length;
 });

 let resultArr=[];
 for(let posArray of posArrayArray){
   for(let pos of posArray){
     resultArr.push(pos);
   }
 }

which has many lines of codes, is there any simpler method?

Upvotes: 0

Views: 1394

Answers (1)

CRice
CRice

Reputation: 32156

My recommendation would be to create another object that counts how many of each element appear in your array. Once you have that, you can sort just by comparing the quantity of each element.

Example:

let arr = [3, 2, 2, 1, 4, 5, 3, 2, 2, 1, 1];

// Do some preprocessing first...
let counts = arr.reduce((counts, num) => {
  counts[num] = (counts[num] || 0) + 1;
  return counts;
}, {});

console.log(counts);

arr.sort(function(p0,p1){
  return counts[p1] - counts[p0];
});

console.log(arr);

Upvotes: 7

Related Questions