댓글 검색 목록

[javascript] Reduce in JavaScript 이해

페이지 정보

작성자 운영자 작성일 20-10-25 17:49 조회 757 댓글 0

배열을 줄이는 것은 여러 값을 단일 값으로 줄여야 할 때 사용할 수 있는 유용한 함수형 프로그래밍 기술입니다. 이 단일 값은 정수로 제한되지 않지만 배열, 객체 등이 될 수 있습니다. 기술 인터뷰에서 reduce가 귀하의 처분에 편리한 방법이라는 것을 알았습니다.

이 기사에서는 ES6의 reduce() 메서드를 소개하고 reduce()를 사용하는 다양한 방법을 살펴보고 map() 및 filter()와 같은 reduce()를 추상화 하는 다른 내장 메서드에 대해 논의합니다.


input.reduce(callback, initialAccValue)
// Note: the `initialAccValue` is optional but effects how reduce() behaves


initialAccValue가 제공되면 입력 배열 내의 모든 항목에 대해 콜백 함수가 호출됩니다. 그런 다음 콜백 함수는 모든 항목을 통과하고 최종 값에 도달 할 때까지 누산기를 변경합니다. 누산기의 최종 값은 궁극적으로 reduce()의 반환 값입니다.


input.reduce((accumulator, item) => {
// What operation(s) should occur for each item?
// What will the accumulator value look like after this operation?
// ?: the accumulator value needs to be explicitly returned.
}, initialValue)


reducer 함수는 최대 4 개의 인수를 사용할 수 있으며 다음과 같습니다.


arr.reduce(callback(accumulator, currentValue[, index[, array]] )[, initialValue]) 



illustrated example of using filter vs reduce to filter fruits out of a collection of food 


reduce()와 인덱스 및 배열 매개 변수에 대한 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce에서 읽을 수 있습니다.


배열을 단일 숫자로 줄이기 


reduce()를 사용하는 일반적인 방법은 배열에 있는 모든 값의 합계를 반환하는 것입니다.


아래 코드에서 값 배열의 각 항목은 콜백 함수의 누산기에 추가됩니다. 누산기의 초기 값은 명시적으로 0으로 설정됩니다. 입력 값을 통한 각 반복 동안 콜백 함수가 호출 될 때마다 이전 반복의 결과 누산기 값으로 전달되기 때문에 누산기는 더 커집니다.


const input = [1, 100, 1000, 10000]
const sum = input.reduce((accumulator, item) => {
return accumulator + item
}, 0) // 11101


위의 reduce 메소드의 각 반복을 살펴보면 다음과 같이 보일 것입니다.


1. accumulator = 0, item = 1

  • the returned accumulator = 1 + 0 = 1

2. accumulator = 1, item = 100

  • the returned accumulator = 1 + 100 = 101

3. accumulator = 101, item = 1000

  • the returned accumulator = 101 + 1000 = 1101

4. accumulator = 1101, item = 10000

  • the final (and only number) returned from the reduce function is 11101. This number is reached because 1101 + 10000 = 11101 and 10000 is the last item in the input array.

map() 및 reduce()로 항목 매핑 


배열의 각 항목에 대해 작업을 수행 한 결과인 새 배열을 반환하려면 map() 또는 reduce()를 사용할 수 있습니다. map()을 사용하면 reduce()보다 더 간결하게 수행 할 수 있지만 둘 중 하나를 사용할 수 있습니다. 아래 예제는 map()과 reduce()를 모두 사용하여 원래 배열에 제곱 된 숫자 버전을 포함하는 배열을 반환하는 방법을 보여줍니다.


map() 사용 

const numbers = [1, 10, 100]
const squared = numbers.map(item => Math.pow(item, 2))
// [1, 100, 10000]


reduce() 사용 

const numbers = [1, 10, 100]
const squared = numbers.reduce((acc, number) => {
acc.push(Math.pow(number, 2))
return acc
}, []) // [1, 100, 10000]


filter() 및 reduce()로 항목 필터링 


특정 기준을 충족하는 값만 유지하기 위해 배열의 값을 필터링 해야 하는 경우 filter()를 사용하거나 기준을 통과하는 항목으로만 손상되는 새 배열을 생성 할 수 있습니다. 아래는 filter() 및 reduce()를 사용하여 숫자 배열에서 짝수만 반환하는 예입니다.


filter() 사용 

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const evenNumbers = numbers.filter(number => number % 2 === 0)
// [2, 4, 6, 8, 10]


reduce() 사용 

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const evenNumbers = numbers.reduce((acc, number) => {
if (number % 2 == 0) {
acc.push(number)
}
return acc
}, [])
// [2, 4, 6, 8, 10]


배열을 단일 객체로 줄이기 


reduce()는 단일 값을 반환해야 하지만 해당 단일 값이 정수 또는 배열 일 필요는 없지만 객체가 될 수도 있습니다. 다음 예제는 배열을 단일 객체로 줄이는 방법을 안내합니다. 이 프롬프트는 VSchool의 reduce 연습에서 가져온 것입니다.


프롬프트는 다음과 같습니다.

잠재적인 투표자의 배열이 주어지면 투표 결과를 나타내는 개체를 반환합니다. 18-25 세의 잠재적 유권자 수, 26-35 세의 수, 36-55 세의 수 및 각 연령대에서 실제로 투표 한 수를 포함하십시오. 이 데이터를 포함하는 결과 개체에는 6 개의 속성이 있어야 합니다. 


유권자의 입력은 다음과 같습니다.


const voters = [
{ name: "Bob", age: 30, voted: true },
{ name: "Jake", age: 32, voted: true },
{ name: "Kate", age: 25, voted: false },
{ name: "Sam", age: 20, voted: false },
{ name: "Phil", age: 21, voted: true },
{ name: "Ed", age: 55, voted: true },
{ name: "Tami", age: 54, voted: true },
{ name: "Mary", age: 31, voted: false },
{ name: "Becky", age: 43, voted: false },
{ name: "Joey", age: 41, voted: true },
{ name: "Jeff", age: 30, voted: true },
{ name: "Zack", age: 19, voted: false },
]


위의 voters 배열과 같은 모양의 배열을 받는 voterResults 함수를 아래에 작성했습니다. 초기 누산기 값을 다음과 같이 설정하기로 결정했습니다.


const initialVotes = {
youngVotes: 0,
youth: 0,
midVotes: 0,
mids: 0,
oldVotes: 0,
olds: 0,
}


initialVotes 객체는 추가되고 기본값이 0 인 모든 잠재적 키를 반환하고 캡슐화 하기 위해 reduce()가 필요했던 최종 값과 동일한 모양이었습니다.이 구조는 총 0을 갖는 범주를 쉽게 캡처합니다. 또한 키를 증가 시키기 전에 키의 현재 값이 존재하는지 확인할 필요가 없습니다.


콜백 함수 내에서 나이와 관련된 조건부 논리를 기반으로 누군가가 속한 피어 그룹을 결정하기 위해 구현해야 하는 논리가 필요했습니다. 해당 피어 데이터는 투표 한 경우 피어 그룹의 투표 데이터를 늘리는데도 사용되었습니다.


function voterResults(arr) {
const initialVotes = {
youngVotes: 0,
youth: 0,
midVotes: 0,
mids: 0,
oldVotes: 0,
olds: 0,
}

const peersToVotePeers = {
youth: "youngVotes",
mids: "midVotes",
olds: "oldVotes",
}

return arr.reduce((acc, voter) => {
if(voter.age < 26)
peers = "youth"
} else if (voter.age < 36) {
peers = "mids"
} else {
peers = "olds"
}
if (!voter.voted) {
// if they didn't vote let's just increment their peers
// for example for { name: "Zack", age: 19, voted: false }
// The peer group would be "youth" and we'd increment acc["youth"] by one
return { ...acc, [peers]: acc[peers] + 1 }
} else {
const votePeers = peersToVotePeers[peers];
// for example for { name: "Jeff", age: 30, voted: true }
// The peer group would is "mids"
// acc["mids"] and acc["midVotes"] are both incremented by one
return {
...acc,
[peers]: acc[peers] + 1,
[votePeers]: acc[votePeers] + 1,
}
}
}, initialVotes)
}


The object output from voterResults(voters) is: 한국어 voterResults (voters)의 개체 출력은 다음과 같습니다.


{ youngVotes: 1,
youth: 4,
midVotes: 3,
mids: 4,
oldVotes: 3,
olds: 4
}


https://www.aboutmonica.com/blog/2020-03-29-understanding-reduce-in-javascript



댓글목록 0

등록된 댓글이 없습니다.

웹학교 로고

온라인 코딩학교

코리아뉴스 2001 - , All right reserved.