ํ๋ก๊ทธ๋๋จธ์ค - ์ด์ด ๋ถ์ธ ์ - js (filter ํจ์)
ํ๋ก๊ทธ๋๋จธ์ค - ์ด์ด ๋ถ์ธ ์ - js
๋ฌธ์
์ ์๊ฐ ๋ด๊ธด ๋ฆฌ์คํธ num_list๊ฐ ์ฃผ์ด์ง๋๋ค. num_list์ ํ์๋ง ์์๋๋ก ์ด์ด ๋ถ์ธ ์์ ์ง์๋ง ์์๋๋ก ์ด์ด ๋ถ์ธ ์์ ํฉ์ returnํ๋๋ก solution ํจ์๋ฅผ ์์ฑํด์ฃผ์ธ์.
์ ํ ์ฌํญ
2 ≤ num_list์ ๊ธธ์ด ≤ 10
1 ≤ num_list์ ์์ ≤ 9
num_list์๋ ์ ์ด๋ ํ ๊ฐ์ฉ์ ์ง์์ ํ์๊ฐ ์์ต๋๋ค.
์ ์ถ๋ ฅ ์
num_list | result |
[3, 4, 5, 2, 1] | 393 |
[5, 7, 8, 3] | 581 |
์ ์ถ๋ ฅ ์ ์ค๋ช
ํ์๋ง ์ด์ด ๋ถ์ธ ์๋ 351์ด๊ณ ์ง์๋ง ์ด์ด ๋ถ์ธ ์๋ 42์ ๋๋ค. ๋ ์์ ํฉ์ 393์ ๋๋ค.
solution.js
filter ํจ์๋ฅผ ์ด์ฉํ ํ์ด>
function solution(num_list) {
const a = num_list.filter(el=>(el%2===1))
const b= num_list.filter(el=>(el%2===0))
return Number(a.join(''))+Number(b.join(''))
}
- ํ์๋ฅผ ๊ฑธ๋ฌ๋ด์ด ๋ฐฐ์ด a ์ ์ ์ฅ
- ์ง์๋ฅผ ๊ฑธ๋ฌ๋ด์ด b์ ์ ์ฅ
- a ๋ฐฐ์ด์ ์์๋ค์ ๋ฌธ์์ด๋ก ํจ์น๊ณ , ์ด๋ฅผ ์ซ์๋ก ๋ณํ
- b ๋ฐฐ์ด์ ์์๋ค์ ๋ฌธ์์ด๋ก ํฉ์น๊ณ , ์ด๋ฅผ ์ซ์๋ก ๋ณํ
- ์์์ ์ป์ ๋ ์ซ์์ ํฉ์ ๋ฐํ
reduce ํจ์๋ฅผ ์ด์ฉํ ํ์ด>
function solution(num_list) {
const { oddSum, evenSum } = num_list.reduce((acc, el) => {
if (el % 2 === 1) {
acc.oddSum.push(el);
} else {
acc.evenSum.push(el);
}
return acc;
}, { oddSum: [], evenSum: [] });
return Number(oddSum.join('')) + Number(evenSum.join(''));
}
filter() ?
filter() ๋ฉ์๋๋ ์ฃผ์ด์ง ํจ์์ ํ ์คํธ๋ฅผ ํต๊ณผํ๋ ๋ชจ๋ ์์๋ฅผ ๋ชจ์ ์๋ก์ด ๋ฐฐ์ด๋ก ๋ฐํํ๋ค.
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// Expected output: Array ["exuberant", "destruction", "present"]