Guest User

Untitled

a guest
Jul 23rd, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.48 KB | None | 0 0
  1. // Given an array, return an array of the top 2 most elements.
  2. // Input: [1, 2, 3, 4, 5, 3, 4] | Output: [3, 4]
  3. // Input: [2, 2, 3, 2, 4, 3, 4] | Output: [2,4]
  4.  
  5. const topTwoElement = nums => {
  6. const arr = [];
  7. nums.forEach(num => {
  8. arr[num] ? arr[num][1]++ : arr[num] = [num, 1];
  9. });
  10.  
  11. arr.sort((a, b) => b[1] - a[1]);
  12. return [arr[0][0], arr[1][0]];
  13. };
  14.  
  15. console.log(topTwoElement([3, 2, 3, 4, 5, 3, 4])); //[3,4]
  16. console.log(topTwoElement([2, 2, 3, 2, 4, 3, 4])); //[2,4]
Add Comment
Please, Sign In to add comment