map, filter ν•¨μˆ˜

kirin.logΒ·2021λ…„ 4μ›” 2일
1
post-custom-banner

πŸš€ map() && filter()

  • 곡톡점: κΈ°μ‘΄ 배열은 κ·ΈλŒ€λ‘œ 두고, 각 λ°°μ—΄ μš”μ†Œλ₯Ό μˆœνšŒν•œ ν›„ μƒˆλ‘œμš΄ 배열을 return
  • 차이점:
    map()은 μ½œλ°±ν•¨μˆ˜κ°€ 적용된 μƒˆ λ°°μ—΄ return
    filter()은 쑰건문을 λ§Œμ‘±ν•œ μš”μ†Œλ“€μ„ μƒˆλ‘œμš΄ λ°°μ—΄λ‘œ return

πŸŽƒ map()

배열을 μˆœνšŒν•˜λ©° μš”μ†Œλ§ˆλ‹€ callback ν•¨μˆ˜ 적용 ν›„ μƒˆλ‘œμš΄ λ°°μ—΄λ‘œ 리턴

πŸŽƒ filter()

배열을 μˆœνšŒν•˜λ©° μš”μ†Œλ§ˆλ‹€ 쑰건 확인 ν›„ 쑰건을 λ§Œμ‘±ν•˜λŠ” μ›μ†Œλ“€λ‘œ κ΅¬μ„±λœ μƒˆλ‘œμš΄ λ°°μ—΄ 리턴
❗ μ§€μ •λœ ν•¨μˆ˜μ˜ κ²°κ³Ό 값을 true둜 λ§Œλ“œλŠ” μ›μ†Œλ“€λ‘œλ§Œ κ΅¬μ„±λœ μƒˆλ‘œμš΄ 배열을 λ°˜ν™˜

예제1


// (1) map
let numbers = [1, 2, 3, 4, 5]

let new_num = numbers.map(function(num) {
			      return num * 2
                          })
console.log(numbers)
// [1, 2, 3, 4, 5]

console.log(new_num)
// [ 2, 4, 6, 8, 10 ]



// (2) filter
let numbers = [1, 2, 3, 4, 5]

let new_num = numbers.filter(number => number % 2 === 0)

console.log(numbers)
// [1, 2, 3, 4, 5]

console.log(new_num)
// [ 2, 4 ]

❗ κΈ°μ‘΄ λ°°μ—΄μ—μ„œ filtering이 ν•„μš”ν•œ 쑰건을 κ±Έμ–΄μ€€λ‹€

예제2


let users = [
  { id:1, name:'id', age:36 },
  { id:2, name:'ds', age:32 },
  { id:3, name:'dw', age:32 },
  { id:4, name:'xc', age:37 },
  { id:5, name:'we', age:25 },
  { id:6, name:'th', age:26 },
  { id:7, name:'gh', age:31 },
  { id:8, name:'jh', age:23 },
]


// 1) 30μ„Έ 이상인 usersλ₯Ό κ±°λ₯Έλ‹€
let over_30 = users.filter( user => user.age >= 30 )

//console.log(over_30)
// [
//  { id: 1, name: 'id', age: 36 },
//  { id: 2, name: 'ds', age: 32 },
//  { id: 3, name: 'dw', age: 32 },
//  { id: 4, name: 'xc', age: 37 },
//  { id: 7, name: 'gh', age: 31 }
// ]


// 2) 30μ„Έ 이상인 users의 name을 좜λ ₯
let over_30 = user.filter( user => user.age >= 30 )

let mapping = over_30.map(function(el) {
  return el.name
})

// console.log(mapping)
// [ 'id', 'ds', 'dw', 'xc', 'gh' ]
profile
boma91@gmail.com
post-custom-banner

0개의 λŒ“κΈ€