JS Basic Let's have some fun with JS :) - filter() / reduce() / map()

Peter Oh·2021년 1월 21일
0

filter()

arr.filter(callback(element[, index[, array]])[, thisArg])

callback
각 요소를 시험할 함수. true를 반환하면 요소를 유지하고, false를 반환하면 버립니다. 다음 세 가지 매개변수를 받습니다.
element
처리할 현재 요소.
index Optional
처리할 현재 요소의 인덱스.
array Optional
filter를 호출한 배열.
thisArg Optional
callback을 실행할 때 this로 사용하는 값.


//제품의 평점으로 검색하기
//filter를 통해 배열안에 있는 요소를 하나씩 검사하면서, 조건에 맞는 경우에 요소를 꺼낼 수 있음
//filter는 callback함수를 요소로 받음, callback함수가 인자로 받을 수 있는 것은 (요소, 인덱스)

const findProductsByStars = (평점) => products.filter((element, index) => {
//logic happens here!
//filter callback => true or false
  return product.평점 === 평점 // products안의 stars와 우리가 인자로 넘긴 stars가 동일하면 true 리턴!!!
})
//리턴문이 한 줄이면 안 써줘도 됨
const findProductsByStars = (stars) => products.filter((product) => product.stars === stars)
//제품의 이름으로 검색하기
// 함수의 이름이 길어도 의미가 명확한 것이 낫다 = 깔끔한 네이밍이 필요!
// 배열의 
const findProductsByName = (productName) => products.filter((product) => { //filter callback => true / false
  return product.name === productName
  return product.name.toLowerCase() === product.toLowerCase()
})

대소문자에 따라서 검색ㅇ기 다르게 되는

해결책은?!

return product.name.toLowerCase().includes(productName.toLowerCase())

//정규표현식 => 
const regExp = new RegExp(productName, 'i') // 'i' flasg // case-insensitive
return product.name.match(regExp) // matching => array, match8ing x => null, undefined!!
// 정규표현식으로 정규표션식 표현

Reduce

arr.reduce(callback[, initialValue])

  1. 누산기accumulator (acc)
  2. 현재 값 (cur)
  3. 현재 인덱스 (idx)
  4. 원본 배열 (src)

callback
배열의 각 요소에 대해 실행할 함수. 다음 네 가지 인수를 받습니다.
accumulator
누산기accmulator는 콜백의 반환값을 누적합니다. 콜백의 이전 반환값 또는, 콜백의 첫 번째 호출이면서 initialValue를 제공한 경우에는 initialValue의 값입니다.
currentValue
처리할 현재 요소.
currentIndex Optional
처리할 현재 요소의 인덱스. initialValue를 제공한 경우 0, 아니면 1부터 시작합니다.
array Optional
reduce()를 호출한 배열.
initialValue Optional
callback의 최초 호출에서 첫 번째 인수에 제공하는 값. 초기값을 제공하지 않으면 배열의 첫 번째 요소를 사용합니다. 빈 배열에서 초기값 없이 reduce()를 호출하면 오류가 발생합니다.

// 모든 제품의 가격을 더하기
const getTotalPrice = () =>
products.reduce((prevValue, product) => {
  console.log('previous value:', prevValue)
  console.log('product element:', product)
  prevValue += 1
  return prevValue
}, 0) // 0 = second argument: initial value
// reduce 함수의 특징, 2번째 인자도 초기값을 설정


const getTotalPrice = () =>
products.reduce((totalPrice, product) => {
  totalPrice = totalPrice + Number(product.price)
  return totalPrice
}, 0)

Map


// spread syntax
// 동일하게 반복되는 product를 ...product로 써서 줄여준다
return{
  ...product,
  adj: newAdj,
}
profile
def backend_engineer():

0개의 댓글