문제
Map, Filter, Reduce - Code Exercises | CroCoder
Map, filter and reduce are the most useful array methods to manipulate arrays and often the hardest to master. Try to solve the given exercises!
www.crocoder.dev
메모
- 처음에는 students 객체 안에 있는 scores의 이름과 값을 변경하는 식으로 답에 접근했지만, 어느 순간 이게 비효율적 방법이란 사실을 깨닫고 방향을 틀었다.
- map으로 원하는 객체 이름을 정해 반환하는 식으로 코드를 작성하면 코드가 더 간결해진다.
- map으로 return을 사용하려면 중괄호로 감싸야 한다.
- 사실 화살표 함수에는 원래 중괄호가 필요하지만, 단순한 식일 때는 생략이 가능하다.
정답
const students = [
{ name: "Alice", scores: [90, 85, 92] },
{ name: "Bob", scores: [75, 80, 85] },
{ name: "Charlie", scores: [90, 95, 100] },
{ name: "Jack", scores: [100, 100, 100] },
];
const obj = students.map(x => {
const sum = x.scores.reduce((a, b) => a + b);
return { name: x.name, average: sum / x.scores.length };
});
const answer = obj.filter(x => x.average > 90);
console.log(answer);