Given an array of bird sightings where every element represents a bird type id, determine the id of the most frequently sighted type. If more than 1 type has been spotted that maximum amount, return the smallest of their ids.
arr = [1,1,2,2,3]
1
and 2
, and one sighting of type 3
. Pick the lower of the two types seen twice: type 1
.INPUT
6
1 2 3 4 5 4 3 2 1 3 4
OUTPUT
3
Explanation
The different types of brids occur in the following frequencies:
- Type 1 : 2
- Type 2 : 2
- Type 3 : 3
- Type 4 : 3
- Type 5 : 1
Two types have a frequency of3
, and the lower of those is type3
.
indexOf
메서드로 최대값과 일치하는 가장 앞쪽의 원소의 인덱스를 구한다.function migratoryBirds(arr) {
let birds = [0, 0, 0, 0, 0];
arr.forEach((e) => {
if(e === 1) birds[0]++;
if(e === 2) birds[1]++;
if(e === 3) birds[2]++;
if(e === 4) birds[3]++;
if(e === 5) birds[4]++;
});
const max = birds.reduce((a,b) => Math.max(a,b));
const maxBirdId = birds.indexOf(max) + 1;
return maxBirdId;
}