리터럴 배열을 받는 JavaScript 함수를 작성해야 합니다. 함수는 배열에서 두 번째로 많이 나타나는 요소를 반환해야 합니다.
예를 들어 -
입력 배열이 -
인 경우const arr = [2, 5, 4, 3, 2, 6, 5, 5, 7, 2, 5];
그러면 출력은 다음과 같아야 합니다. -
const output = 2;
예시
const arr = [2, 5, 4, 3, 2, 6, 5, 5, 7, 2, 5];
const findSecondMost = (arr = []) => {
const map={};
arr.forEach(el => {
if(map.hasOwnProperty(el)){
map[el]++; }else{ map[el] = 1;
}
})
const sorted = Object.keys(map).sort((a,b) => map[b]-map[a]);
return sorted[1];
};
console.log(findSecondMost(arr)); 출력
콘솔의 출력은 -
2