์ต๋น๊ฐ์ ์ฃผ์ด์ง ๊ฐ ์ค์์ ๊ฐ์ฅ ์์ฃผ ๋์ค๋ ๊ฐ์ ์๋ฏธํฉ๋๋ค. ์ ์ ๋ฐฐ์ด array๊ฐ ๋งค๊ฐ๋ณ์๋ก ์ฃผ์ด์ง ๋, ์ต๋น๊ฐ์ return ํ๋๋ก solution ํจ์๋ฅผ ์์ฑํด๋ณด์ธ์. ์ต๋น๊ฐ์ด ์ฌ๋ฌ ๊ฐ๋ฉด -1์ return ํฉ๋๋ค.
array | result |
---|---|
[1, 2, 3, 3, 3, 4] | 3 |
[1, 1, 2, 2] | -1 |
[1] | 1 |
function solution(array) {
const counts = array.reduce((a, c) => (a[c] ? { ...a, [c]: a[c] + 1 } : { ...a, [c]: 1 }), {});
const max = Math.max(...Object.values(counts));
const modes = Object.keys(counts).filter(key => counts[key] === max);
return modes.length === 1 ? +modes[0] : -1;
}