Skip to content
Advertisement

How can I return the mode that appeared first in an array in Javascript?

I want to create a function that will return the number with highest frequency(mode). For example: if array contains [10, 4, 5, 2, 4] the output should be 4. If there is more than one mode, I want to return the one that appeared in the array first (ie. [10,2,5, 4, 5, 2, 4] should return 2 because it appeared first. If there is no mode, I want to return -1. The array will not be empty. Below is my attempt

JavaScript

Advertisement

Answer

If you only need the first one that its repeated you can try this approach

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement