[JS/React] 컴포넌트 내부에서 reduce 사용해 평균값 구하기

hyeonze·2022년 1월 13일
0

데이터 형태

const mainVisualMockData = {
  update_date: 'January 11, 2022',
  title: 'The Unconventional Gallery',
  user_id: 'MAKEMEPULSE',
  location: 'FRANCE',
  total: 50, // 하드코딩을 피하고싶음
  scores: [
    { color: 'red', item: 'DESIGN', score: 30 },
    { color: 'green', item: 'USABILITY', score: 50 },
    { color: 'blue', item: 'CREATIVITY', score: 70 },
  ],
};

데이터 사용할 위치

export default function MainVisual() {
  return (
    ...
	<MainVisualMainInformationStrong>
  	  {/* {mainVisualMockData.total} */} // 하드코딩을 피하고싶음
  	  {mainVisualMockData.scores.reduce(
            (acc, curr) => acc + curr.score,
            0
          ) / mainVisualMockData.scores.length}
        </MainVisualMainInformationStrong>
    ...
  );
}

뜯어보기

const scores = [{
  score: 30
},{
  score: 50
},{
  score: 70
}];

scores.reduce((acc, curr) => acc + curr.score, 0) / scores.length; // 50

reduce() 메서드

배열의 각 요소에 대해 주어진 리듀서 함수를 실행하고, 하나의 결과값을 반환

ex. 배열의 모든 값 합산

var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);
// sum is 6

ex. 화살표 함수 활용

var total = [ 0, 1, 2, 3 ].reduce(
  ( accumulator, currentValue ) => accumulator + currentValue,
  0
);

ex. 객체 배열에서의 값 합산

var initialValue = 0;
var sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) {
    return accumulator + currentValue.x;
},initialValue)

console.log(sum) // logs 6

ex. 화살표함수 활용

var initialValue = 0;
var sum = [{x: 1}, {x:2}, {x:3}].reduce(
    (accumulator, currentValue) => accumulator + currentValue.x
    ,initialValue
);

console.log(sum) // logs 6

객체배열에서 응용하기

profile
Advanced thinking should be put into advanced code.

0개의 댓글