_.filter_.reduce.png)
자바스크립트에서 map(), filter(), reduce() 메소드는 배열 요소를 나열하거나, 특정 조건에 맞게 보여줄 때 자주 쓰인다.
예제 배열
const listData = [
{
id: 1,
text: 'test1',
},
{
id: 2,
text: 'test2',
},
{
id: 3,
text: 'test3',
},
{
id: 4,
text: 'test4',
},
{
id: 5,
text: 'test5',
},
]
// Array.prototype.map()
arr.map(callback(currentValue[, index[, array]])[, thisArg])
const realMapResult = listData.map(list => list.text)
console.log(realMapResult)
// output: ["test1", "test2", "test3", "test4", "test5"]
실제 map()과 같은 결과를 얻기 위해선??
const mockMap = list => {
let result = [] // map()은 새로운 배열을 반환
for (const i of list) {
result.push(i.text)
}
return result
}
const result = mockMap(listData)
console.log(result)
// Array.prototype.filter()
arr.filter(callback(element[, index[, array]])[, thisArg])
const realFilterResult = listData.filter(list => list.text !== 'test1')
console.log(realFilterResult)
// output: [
// {
// id: 1,
// text: 'test2',
// },
// {
// id: 3,
// text: 'test3',
// },
// {
// id: 4,
// text: 'test4',
// },
// {
// id: 5,
// text: 'test5',
// },
// ]
실제 filter()과 같은 결과를 얻기 위해선??
const mockFilter = list => {
let result = [] // filter() 역시 새로운 배열을 반환
for (const i of list) {
if (i.text !== 'test1') {
result.push(i) // 해당 조건에 맞는 객체를 push
}
}
return result
}
const result = mockFilter(listData)
console.log(result)
reducer() 함수는 네 개의 인자를 받는다.
initialValue가 있을 경우 initialValue이며, 없을 경우 콜백의 반환값을 누적initialValue가 있을 경우 0, 아니면 1부터 시작const array1 = [1, 2, 3, 4]
const resultOfReducer = array1.reduce(
(accumulator, currentValue, currentIndex, array) => {
console.log('accumulator', accumulator) // output: 10 11 13 16
console.log('currentValue', currentValue) // output: 1 2 3 4
console.log('currentIndex', currentIndex) // output: 0 1 2 3
console.log('array', array) // output: [1, 2, 3, 4]
return accumulator + currentValue
},
10//initValue
)
console.log(resultOfReducer) // output: 20(10 + 1 + 2 + 3 + 4)
//initValue가 없으면 (1 + 2 + 3 + 4)
//string
const resultOfReducer = listData.reduce(
(accumulator, currentValue, currentIndex, array) => {
return accumulator + currentValue.text + ' '
},
''
)
console.log(resultOfReducer)// "test1 test2 test3 test4 test5"