Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- mysql error
- mysql
- react map error
- spring framework
- jdk
- mac mariadb
- sts
- join
- ps
- 도커파일
- docker container
- 도커
- springboot jar
- 관리
- root
- DB
- brew install mariadb
- jar deploy
- install
- Access denied for user ''@'localhost'
- Docker
- Dockerfile
- Oracle
- 설치
- jar배포
- springboot
- systemd
- map is not a function
- sudo
- 파일 시스템
Archives
- Today
- Total
Yoon.s
[javascript] reduce() 함수 본문
reduce()
배열의 각 요소에 대해 주어진 reducer 함수를 실행하고, 하나의 결과값을 반환함
arr.reduce(callback[, initialValue])
- callback : 배열의 각 요소에 대해 실행할 함수
- *accumulator : 콜백의 반환값을 누적함 (initialValue가 존재하면 그것이 accumulator)
- *currentValue : 처리할 현재 요소
- currentIndex : 현재 요소의 인덱스 (option) - initialValue 있으면 0, 아니면 1
- array : reduce()를 호출한 배열 (option)
- initialValue : callback의 최초 호출에서 첫 번째 인수에 제공하는 값. 초기값을 제공하지 않으면 배열의 첫 번째 요소를 사용
- 반환값 : 누적된 호출 값
설명. 배열에 있는 값 모두 더하는 코드
const array1 = [1, 2, 3, 4];
// 1 + 2 + 3 + 4
const reducer = array1.reduce(((initialValue, currentValue, currentIndex, array) => {
return initialValue + currentValue;
});
// 10 + 1 + 2 + 3 + 4
const reducer = array1.reduce(((initialValue, currentValue, currentIndex, array) => {
return initialValue + currentValue;
}, 10);
1) 앞의 initValue가 없는 reduce() 함수는
- initialValue은 처음엔 initValue를 가져오고 다음 부턴 리턴값을 저장하고 있음
- currentValue값은 배열의 첫 번째부터
- initValue 값이 없기 때문에 currentIndex는 1부터 시작
- array는 array1
예제. 객체 내 값 인스턴스 개수세기
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
var countedNames = names.reduce(function (allNames, name) {
if (name in allNames) {
allNames[name]++;
}
else {
allNames[name] = 1;
}
return allNames;
}, {});
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
countedNames의 함수는 names배열을 reduce
-> allNames에 리턴값을 저장하고 name은 첫번째 값부터 넣을 것임.
참조사이트:
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
'프론트 > Javascript' 카테고리의 다른 글
[javascript] split(), sort(), reverse(), join() 함수 (0) | 2020.09.23 |
---|---|
[javascript] substr(), substring(), slice() 비교 (0) | 2020.09.09 |
[javascript] filter 함수 (0) | 2020.09.07 |
Comments