Return the top k most frequent elements

Problem description is here https://leetcode.com/problems/top-k-frequent-elements/

Explanation is here https://www.youtube.com/watch?v=qaiQLTS_NZw&ab_channel=saghanmudbhari

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var topKFrequent = function(nums, k) {
const map = new Map();
nums.forEach(num=>{
if(!map.has(num)){
map.set(num,1)
}
else{
map.set(num, map.get(num)+1)
}
});

const sortedMap = new Map([...map.entries()].sort((a,b)=>b[1]-a[1]));
const sortedArray = Array.from(sortedMap,(k)=>[k[0],k[1]]);
return sortedArray.slice(0,k).map(element=>element[0])

};