Array.reduce(cbfunction(accumulator,currentItemInArray,index)
//write function context;
,initialValue);
Array.reduce((누적값, 현재값, 인덱스, 요소) => {
return 결과;
}, 초기값);
//초기값을 설정하지 않으면 0번째 인덱스의 값이 초기값이 된다.
const arrayItems = [1, 2, 3, 4, 5, 6];
const sum = arrayItems.reduce(function (acc, cur, idx) {
accumulator = accumulator + currentItemInArray;
return accumulator;
}, 0);
// sum = 21
ArrayForReduce = [3, 7, 10, 15, 66, 13, 25, 50, 4, 77, 91];
result = ArrayForReduce.reduce((acc, cur, i) => {
return acc + cur;
});
> 361
위와 같은 방법으로도 reduce를 활용할 수 있지만,
reduce는 사칙연산뿐만 아니라 다양한 기능을 수행할 수 있다.
result = oneTwoThree.reduce((acc, cur) => {
acc.push(cur % 2 ? '홀수' : '짝수');
return acc;
}, []);
result; // ['홀수', '짝수', '홀수']
삼항연산자로 홀,짝수를 구할 수 있는 이유
condition ? true : false
위의 예시에서 %2를 통해 나오는 값은 1 또는 0 뿐이다.
true:false는 boolian 값으로 1이 되면 true(홀수), 0이 되면 false(짝수).
끝에 초기값을 배열로 설정하면 map과 같이 사용할 수 있고,
조건을 붙인다면, filter와 같이 사용할 수도 있다.result = oneTwoThree.reduce((acc, cur) => { if (cur % 2) acc.push(cur); return acc; }, []); result; // [1, 3] ```
const ArrayForReduce = [3,7,10,15,66,13,25,50,4,77,91];
result = ArrayForReduce.reduce((acc,cur)=>{
return acc + cur;},0);
result = 361
const numbers = [2, -5, -123, 59, -5480, 24, 0, -69, 349, 3];
const result = numbers.reduce(
(acc, cur, idx) => {
if (cur < 0) {
// 처리할 현재 요소가 음수일 경우
acc[0]++;
} else if (cur > 0) {
// 처리할 현재 요소가 양수일 경우
acc[1]++;
}
return acc;
},
[0, 0]
);
console.log(result); // [4, 5]
const promiseFactory = (time) => {
return new Promise((resolve, reject) => {
console.log(time);
setTimeout(resolve, time);
});
};
[1000, 2000, 3000, 4000].reduce((acc, cur) => {
return acc.then(() => promiseFactory(cur));
}, Promise.resolve());
// 바로 1000
// 1초 후 2000
// 2초 후 3000
// 3초 후 4000
//Given an input //입력값
const fruits = [
'apples',
'apples',
'bananas',
'oranges',
'apples',
'oranges',
'bananas',
'grapes',
];
// should give an output of // 기대값
const count = { apples: 3, oranges: 2, bananas: 2, grapes: 1 };
const fruits = [
'apples',
'apples',
'bananas',
'oranges',
'apples',
'oranges',
'bananas',
'grapes',
];
function countOccurrence(accumulator, currentFruit) {
const currentFruitCount = accumulator[currentFruit];
if (currentFruitCount) {
accumulator[currentFruit] = currentFruitCount + 1;
} else {
accumulator[currentFruit] = 1;
}
return accumulator;
}
const initialValue = {};
const count = fruits.reduce(countOccurrence, initialValue);
const fruits = [
'apples',
'apples',
'bananas',
'oranges',
'apples',
'oranges',
'bananas',
'grapes',
];
// current element is 'apples'
function countOccurrence(accumulator = {}, currentFruit = 'apples') {
// since currentFruit = 'apples' then accumulator[currentFruit] = accumulator['apples']
const currentFruitCount = accumulator[currentFruit];
// currentFruitCount will be null since accumulator is an empty object
if (currentFruitCount) {
accumulator[currentFruit] = currentFruitCount + 1;
} else {
// this block will run since accumulator is empty
// currentFruit = 'apples'
accumulator['apples'] = 1;
// accumulator should look like this: { 'apples': 1 }
}
return accumulator; // which is { 'apples': 1 };
const fruits = [
'apples',
'apples',
'bananas',
'oranges',
'apples',
'oranges',
'bananas',
'grapes',
];
// current element is 'apples'
function countOccurrence(accumulator = { apples: 1 }, currentFruit = 'apples') {
// since currentFruit = 'apples' then accumulator[currentFruit] = accumulator['apples']
const currentFruitCount = accumulator[currentFruit];
// currentFruitCount will be 1
if (currentFruitCount) {
// this block will run since currentFruitCount is 1
// currentFruit = 'apples'
accumulator['apples'] = 1 + 1;
// accumulator should look like this: { 'apples': 2 }
} else {
accumulator[currentFruit] = 1;
}
return accumulator; // which is { 'apples': 2 };
const fruits = [
'apples',
'apples',
'bananas',
'oranges',
'apples',
'oranges',
'bananas',
'grapes',
];
// current element is 'bananas'
function countOccurrence(
accumulator = { apples: 2 },
currentFruit = 'bananas'
) {
// since currentFruit = 'bananas' then accumulator[currentFruit] = accumulator['bananas']
const currentFruitCount = accumulator[currentFruit];
// currentFruitCount will be null since accumulator doesn't contain 'bananas'
if (currentFruitCount) {
accumulator[currentFruit] = currentFruitCount + 1;
} else {
// this block will run since currentFruitCount is null
// currentFruit = 'bananas'
accumulator['bananas'] = 1;
}
return accumulator; // which is { 'apples': 2, 'bananas': 1 };
}