JSFiddle - React, Tailwind, and code Playground

by Prathameshsb

JavaScript

var test = function(arr, k) {
	let map = new Map();
  for(const c of arr) {
  	map.set(c, (map.get(c) || 0) + 1);
  }
  
  let bucket = new Array(arr.length + 1).fill().map(() => []);
  
  for(const [key, val] of map.entries()) {
  	bucket[val].push(key);
  }
  
  let result = [];
  
  for(let i = bucket.length - 1; i >= k; i--) {
  	result.push(...bucket[i]);
    if(result.length > k) break;
  }
  
  return result;
}

console.log(test([1,1,1,2,2,4], 2));