Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Given an array, return an array of the top 2 most elements.
- // Input: [1, 2, 3, 4, 5, 3, 4] | Output: [3, 4]
- // Input: [2, 2, 3, 2, 4, 3, 4] | Output: [2,4]
- const topTwoElement = nums => {
- const arr = [];
- nums.forEach(num => {
- arr[num] ? arr[num][1]++ : arr[num] = [num, 1];
- });
- arr.sort((a, b) => b[1] - a[1]);
- return [arr[0][0], arr[1][0]];
- };
- console.log(topTwoElement([3, 2, 3, 4, 5, 3, 4])); //[3,4]
- console.log(topTwoElement([2, 2, 3, 2, 4, 3, 4])); //[2,4]
Add Comment
Please, Sign In to add comment