> For the complete documentation index, see [llms.txt](https://triplexlab.gitbook.io/vanilla-js/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://triplexlab.gitbook.io/vanilla-js/practice/reduce.md).

# 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="/files/-M5Xen3ZFiUfIcKUHQBC" %}
reduce 연습
{% endfile %}
