본문 바로가기

Frontend Study - 2/coding test

Coding test : Reduce 메소드 사용예시,

 

주어진 배열의 각 요소에 대하여 reducer함수를 실행하고 하나의 결과값을 반환한다. 

arr.reduce(callback, initialValue)

 

 

사용예시

 

 

1. 배열안의 합.

const total = [2,4,6,8,10].reduce((acc, cur) => acc + cur)

const total = [2,4,6,8,10].reduce((acc, cur) => acc + cur, 1)

초기값을 넣어줄 수 있고 생략할 수 도 있다.

 

- 초기값을 생략하면 [2,4,6,8,10] 배열의

acc (accumulator) 시작 값은 0번 인덱스(2)가 되고, cur (currentValue) 시작 값은 1번 인덱스(4)가 된다.

 

- 초기값을 넣어줬을 경우 acc (accumulator) 시작 값은 initialValue(1)가 되고, cur (currentValue) 시작 값은 0번 인덱스(2)가 된다.

 

 

 

const solution = (numbers) => numbers.reduce((acc, cur) => (acc + cur)) / numbers.length

numbers.length로 나누어주는 것을 reduce안에 넣어버림.

 

 

2. 객체 배열에서의 합

[{num : 2}, {num : 4}, {num : 6}].reduce((acc, cur) => {
	return acc + cur.num
	}, 0)

첫번째 값 initialValue를 꼭 넣어주어야 한다. 넣어주지 않으면 0번째 인덱스 값이 바로 acc로 들어가버려 에러가 난다. 모든 객체들이 cur.num을 거칠 수 있도록 초기값을 설정.

 

 

3. 배열 합치기

[[0,1] , [2,3] , [4, [5,6]]].reduce((acc, cur) => {
	return acc.concat(cur)
	}, [])

 

4. 스프레드 연산자 이용해서 객체안에 담긴 배열 합치기 

let friends = [{
  name: 'Anna',
  books: ['Bible', 'Harry Potter'],
  age: 21
}, {
  name: 'Bob',
  books: ['War and peace', 'Romeo and Juliet'],
  age: 26
}, {
  name: 'Alice',
  books: ['The Lord of the Rings', 'The Shining'],
  age: 18
}];

let books = friends.reduce((acc, cur) => {
  return [...acc, ...cur.books];
}, []);

 

5. 인스턴스의 개수 세기

const lists = ["아야", "어여", "오요", "우유", "으이", "아야"]

const listCount = lists.reduce((totalList, list) => {
  if (list in totalList) {
    totalList[list]++;
  } else {
    totalList[list] = 1;
  }

  return totalList;
}, {});

// listCount = { '아야': 2, '어여': 1, '오요': 1, '우유': 1, '으이' : 1 }

 

6. 속성으로 객체 분류하기.

 

const people = [
  { name: "고고", age: 20 },
  { name: "가가", age: 20 },
  { name: "기기", age: 21 },
];

const ageSorting = (array, property) => {
  return array.reduce((acc, cur) => {
    let key = cur[property];

    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(cur);

    return acc;
  }, {});
};

const peopleAge = ageSorting(people, "age");

console.log(peopleAge);

 

 

참고사이트

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

'Frontend Study - 2 > coding test' 카테고리의 다른 글

coding test 기초 1 ~ 7  (0) 2022.07.02