The result should be a 2 element array with the 2 number that are most frequent; I can return the top 2 most amount of times a number has been spotted (my //comments). But I can not figure out how to return the correct keys from the pairs object that appear the most times. Please help.
/* majorityElementTopTwo
* Write a function which accept an array of integers and returns in a new two item array
* the two integers in the input that appear most frequently.
* majorityElementTopTwo([3,3,1,2,1,1,4,4,4,4]); // [4,1]
*/
function majorityElementTopTwo(array) {
let result = [];
let pairs = {};
for (let i = 0; i < array.length; i++) {
if (array[i] in pairs) {
pairs[array[i]] += 1;
} else {
pairs[array[i]] = 1;
}
}
return pairs;
// obj.sort();
// for(let i = obj.length; i > 0; i--){
// let num = obj.pop();
// console.log(num);
// result.push(num);
// }
// return result.slice(0,2);
}
console.log(majorityElementTopTwo([3, 3, 1, 2, 1, 1, 4, 4, 4, 4])); // [4,1]