인프런 커뮤니티 질문&답변
reduce, foreach 메서드로 풀어도 되나요
작성
·
296
0
안녕하세요 강사님.
저는 이번 풀이에서 forEach로 홀수 배열을 만들고
reduce로 합을, sort로 최솟값을 구했는데
이렇게 푸는 것과 for문으로 푸는 것의 차이가 궁금합니다.
메서드를 많이 쓰면 그만큼 효율이 떨어질까요?
// 홀수
function solution(arr) {
let odd = [];
let sum_odd = 0;
let min_odd = 0;
arr.forEach((num) => {
if (num % 2 === 1) {
odd.push(num);
}
});
sum_odd = odd.reduce((a, b) => a + b);
min_odd = odd.sort((a, b) => a - b)[0];
return `${sum_odd} ${min_odd}`;
}
console.log(solution([12, 77, 38, 41, 53, 92, 85])); // 256 41
답변 1
0
reduce를 쓰신다면 forEach 와 reduce 둘다 loop을 하기 때문에 처음부터 forEach 없이 하시면 더 간단히 쓸 수 있습니다. Method를 사용할 때는 효율성이 떨어지지는 않지만 technical interview에서 면접관이 method를 사용하지 말라고 요구할 경우를 대비해서 연습하시는게 좋을 것 같아요. 그리고 위에서 assign된 variable들은 변하지 않기 때문에 const 또는 var 로 하시는게 괜찮을것 같습니다. ^^
function mySolution(arr) {
let sum = 0;
const filter = arr.reduce((oddNumbers, number) => {
if (number % 2 === 1) {
oddNumbers.push(number);
sum += number;
}
return oddNumbers;
}, []);
const sumUp = filter.reduce((prev, curr) => prev + curr);
filteredArr = filter.sort((a, b) => a - b);
console.log(`The array is ${filter}`);
console.log(`Sum of all odd numbers is ${sumUp}`);
console.log(`The smallest odd number is ${filteredArr[0]}`);
}
mySolution([12, 77, 38, 41, 53, 92, 85]);




