# reduce

### 어떤 기준에 의한 데이터들을 group해서 배열에 담기

```javascript
 var people = [
  { _id: 1,  name: 'iroMan', actor: '로버트 다우니 주니어', alias: '아이어맨', age: 21 },
  { _id: 2, name: 'Jane', actor:'toto', alias: 'dddd', age: 40 },
  { _id: 3, name: 'captainAmerica', actor:'크리스 에반스', alias: '캡틴 아메리카', age: 40 },
  { _id: 4, name: 'captainAmerica', actor:'크리스 에반스', alias: '캡틴 아메리카', age: 40 }
];
```

```javascript
const groupBy = (objectArray, property) => {
return objectArray.reduce((acc, cur, idx) => {
    var key = cur[property];
    if(!acc[key]){      // 누적되는 age가 없으면 
        acc[key] = [];  // 누적되는 age를 key명으로 빈배열을 만들어준다.
    }
     acc[key].push(cur);
     return acc;
}, {}); // acc의 초기 값 빈객체를 만들어준다. 1)
};

var groupedId = groupBy(people, '_id');
console.log(groupedId)

var groupedAge = groupBy(people, 'age');
console.log(groupedAge)
```

### 배열의 각 원소에 원하는 키명을 넣기&#x20;

```javascript
//  ❌ Bad Code
const groupBy = (objectArray) => {
     return objectArray.reduce((acc, cur, idx) => { 
          acc['key_'+ (idx + 1)] = cur    // 배열의 각 원소에 원하는 키명을 넣어서, 
          return acc;                     // acc누적된 값을 리턴합니다.
     }, {}); // acc의 초기 값 빈객체를 만들어준다. 1)
};

var groupedAge = groupBy(people);
console.log(groupedAge);
```

```javascript
//  ✅ Good Code
const result = people.reduce((acc, cur, idx) => {
    return ({...acc, ['key_'+(idx+1)] : cur})
},{});

console.log(result);
```

> 이렇게 Spread Syntax 사용하면 좋은점은 만약 acc 값을 덮어씌우고 싶다면  , 콤마 뒤에다가 원하는 값으로 업데이트를 할수 있습니다.&#x20;

**결과) 👇👇**

![](https://3843212257-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LqOIAZJ26UmArDUcS8p%2F-MjCn7sg8-Kx6EcRvfgB%2F-MjCnBUa7tl0FOfieMjg%2F%E1%84%89%E1%85%B3%E1%84%8F%E1%85%B3%E1%84%85%E1%85%B5%E1%86%AB%E1%84%89%E1%85%A3%E1%86%BA%202021-09-10%20%E1%84%8B%E1%85%A9%E1%84%92%E1%85%AE%2012.41.59.png?alt=media\&token=e075c706-5f3f-4ec8-b5bb-e9df419277f7)

{% file src="<https://3843212257-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LqOIAZJ26UmArDUcS8p%2F-M5XegMSWf96IKP7g03z%2F-M5Xen3ZFiUfIcKUHQBC%2Freduce.html?alt=media&token=c4fd4a1b-2db3-4432-b533-2258a0530895>" %}
reduce 연습
{% endfile %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://triplexlab.gitbook.io/vanilla-js/practice/reduce.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
