How to properly use Javascript Map, Filter, and Reduce
자바스크립트 고차함수 map, filter, reduce 사용하기
Sample Player list Array
const players = [
  {
    id: 10,
    name: "Jan Vertonghen",
    status: "Goal keeper",
    totalMatch: 400,
    retired: true,
  },
  {
    id: 2,
    name: "Paulo Wanchope",
    status: "Attacker",
    totalMatch: 200,
    retired: false,
  },
  {
    id: 41,
    name: "Ronny Johnsen",
    status: "Goal keeper",
    totalMatch: 300,
    retired: true,
  },
  {
    id: 99,
    name: "Gilberto Silva",
    status: "Attacker",
    totalMatch: 140,
    retired: false,
  },
]Map
map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환한다.
js Map example
const array1 = [1, 4, 9, 16]
// pass a function to map
const map1 = array1.map(x => x * 2)
console.log(map1)
// expected output: Array [2, 8, 18, 32]const fruits = [
  { id: 2, name: "banana" },
  { id: 4, name: "apple" },
  { id: 6, name: "cherry" },
  { id: 8, name: "grape" },
]
const fruitsIds = fruits.map(fruit => fruit.id)
// expected output: [2, 4, 6, 8]Filter
filter() 메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환한다.
js Filter example
const words = ["spray", "limit", "elite", "exuberant", "destruction", "present"]
const result = words.filter(word => word.length > 6)
console.log(result)
// expected output: Array ["exuberant", "destruction", "present"]const attackers = players.filter(player => player.status === "Attacker")
/*
(2) [{…}, {…}]
0: {id: 2, name: "Paulo Wanchope", status: "Attacker", totalMatch: 200, retired: false}
1: {id: 99, name: "Gilberto Silva", status: "Attacker", totalMatch: 140, retired: false}
*/Reduce
reduce() 메서드는 배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환한다.
js Reduce example
const array1 = [1, 2, 3, 4]
const reducer = (accumulator, currentValue) => accumulator + currentValue
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer))
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5))
// expected output: 15Compute sum based on object array key
const totalMatchs = players.reduce(function(accumulator, player) {
  return accumulator + player.totalMatch
}, 0)
// totalMatchs : 1040refactor
const totalMatchs = players.reduce((acc, player) => acc + player.totalMatchs, 0)리듀서 함수는 네 개의 인자를 가진다.
- acc: 누산기accumulator
- cur: 현재 값
- idx: 현재 인덱스
- src: 원본 배열
accmulator
콜백의 반환값을 누적한다. 콜백의 이전 반환값 또는, 콜백의 첫 번째 호출이면서 initialValue를 제공한 경우에는 initialValue의 값이다.
currentValue
처리할 현재 요소
initialValue (Optional)
callback의 최초 호출에서 첫 번째 인수에 제공하는 값. 초기값을 제공하지 않으면 배열의 첫 번째 요소를 사용한다. 빈 배열에서 초기값 없이 reduce()를 호출하면 오류가 발생한다.
Useful Map & Filter & Reduce
Create search auto-complete input using Map & Filter & Reduce
class List extends React.Component {
  constructor(props) {
    super(props)
    this.state = { filter: "" }
  }
  handleChange(value, e) {
    this.setState({ filter: value })
  }
  render() {
    const list = this.props.list
      .reduce((acc, currentValue) => acc.concat(currentValue))
      .filter(item => item.title.includes(this.state.filter))
      .map(item => <ListItem key={item.id} name={item.title} />)
    return (
      <div>
        <Input hChange={this.handleChange.bind(this)} />
        <ul>{list}</ul>
      </div>
    )
  }
}polyfills cdn
폴리필 cdn
댓글