Array Helper Methods in ES6

Callback function

Callback function ์ด๋ž€? - MDN

: A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of rotine or action.

์ฝœ๋ฐฑ ํ•จ์ˆ˜(A)๋Š” ๋‹ค๋ฅธ ํ•จ์ˆ˜(B)์˜ ์ธ์ž๋กœ ๋„˜๊ฒจ์ง€๋Š” ํ•จ์ˆ˜๋กœ,

๋‹ค๋ฅธ ํ•จ์ˆ˜(B)์˜ ๋‚ด๋ถ€์—์„œ ์‹คํ–‰๋˜๋Š” ํ•จ์ˆ˜(A)๋ฅผ ๋งํ•œ๋‹ค.

1. map()

Returns a new array containing the results of calling callbackFn on every element in this array.

ex)

['1', '2','3'].map(Number)

const numbers = [0, 9, 99]

function addOne(number) {
    return number + 1
}
const newNumbers1 = numbers.map(addOne)
console.log(newNumbers1)

const newNumbers2 = numbers.map(function(number) {
    // [0, 9, 99] ๋ฅผ ์ˆœํšŒํ•˜๋ฉฐ, ๊ฐ ์š”์†Œ๋ฅผ (number) ์ž๋ฆฌ์— ๋„ฃ๋Š”๋‹ค.
    // ๊ทธ๋ฆฌ๊ณ  ๋ฆฌํ„ด๋œ ๊ฐ’์„ ์ƒˆ๋กœ์šด ๋ฐฐ์—ด์— ๋„ฃ๊ณ  ๋งˆ์ง€๋ง‰์— ๋ฆฌํ„ดํ•œ๋‹ค.
    return number + 1
})
console.log(newNumbers2)

2. forEach()

Calls a callback function for each element in the array.

ex)

// 2. forEach
//   : return ๊ฐ’์ด ์—†๋‹ค!

let sum = 0
nums = [1,2,3]
nums.forEach(function(number){
    // numbers์˜ ๊ฐ ์š”์†Œ๋ฅผ number ์ž๋ฆฌ์— ๋„ฃ๊ณ ,
    // ๋‚˜๋จธ์ง€๋Š” ์•Œ์•„์„œ ํ•ด๋ผ! return ์—†๋‹ค!
    sum += number
})

console.log('๋ฐ?'+nums)

3. filter()

Returns the found element in the array, if some element in the array satisfies the testing callback function, or undefined if not found.

ex)

// 3. filter
const odds = [1,2,3].filter(function(number) {
    // ๊ฐ ์š”์†Œ๋ฅผ number ์ž๋ฆฌ์— ๋„ฃ๊ณ ,
    // return์ด true์ธ ์š”์†Œ๋“ค๋งŒ ๋ชจ์•„์„œ ์ƒˆ๋กœ์šด ๋ฐฐ์—ด๋กœ return
    return number %2
})

console.log(odds)

4. find()

Returns the found element in the array, if some element in the array satisfies the testing callback function, or undefined if not found.

ex)

// 4. find
const evens = [1,2,3,4].find(function(number) {
 // filter()์™€๋Š” ๋‹ค๋ฅด๊ฒŒ find()๋Š” ํ•จ์ˆ˜๊ฐ€ true๋ฅผ returnํ•˜๋ฉด ๋ฐ”๋กœ ์ข…๋ฃŒ๋จ
    return !(number & 1)
})
console.log('์ง์ˆ˜ ์ฐพ์•„๋ผ~ ', evens)

5. every()

Returns true if every element in this array satisfies the testing callback function

ex)

// 5. every
const pass = [50,60,70,80,90].every(function(number){
    // ๋ชจ๋“  ์›์†Œ๋“ค์ด ์กฐ๊ฑด์„ ํ†ต๊ณผํ•˜๋ฉด true, ์•„๋‹ˆ๋ฉด false return
    return number > 40
})
console.log('ํ†ต๊ณผ์ž…๋‹ˆ๊นŒ? ',pass)

Last updated