View

TIL | Node.js_filter()

Melody:) 2021. 10. 4. 21:33

Array.prototype.filter()

filter()메서드는 제공된 함수로 구현된 테스트를 통과하는 모든 요소가 포함된 새 배열 을 만듭니다.

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"]

사용법

// Arrow function
filter((element) => { ... } )
filter((element, index) => { ... } )
filter((element, index, array) => { ... } )

// Callback function
filter(callbackFn)
filter(callbackFn, thisArg)

// Inline callback function
filter(function callbackFn(element) { ... })
filter(function callbackFn(element, index) { ... })
filter(function callbackFn(element, index, array){ ... })
filter(function callbackFn(element, index, array) { ... }, thisArg)

매개변수

  • callback : 함수는 배열의 각 요소를 테스트하기 위한 술어입니다. true요소를 유지하거나 false, 그렇지 않은 경우 강제하는 값을 반환합니다
    [3가지 인자]
    1. currentValue : 배열에서 처리 중인 현재 요소.
    2. index : 배열에서 처리 중인 현재 요소의 인덱스.(Optional)
    3. array : filter()을 호출한 배열.(Optional)
  • thisArg : callback을 실행할 때 this로 사용되는 값.(Optional)

리턴값

  • 테스트를 통과한 요소가 있는 새 배열, 테스트를 통과한 요소가 없으면 빈 배열이 반환

예제

  • 배열에서 검색
let fruits = ['apple', 'banana', 'grapes', 'mango', 'orange']

/**
 * Filter array items based on search criteria (query)
 */
function filterItems(arr, query) {
  return arr.filter(function(el) {
    return el.toLowerCase().indexOf(query.toLowerCase()) !== -1
  })
}

console.log(filterItems(fruits, 'ap'))  // ['apple', 'grapes']
console.log(filterItems(fruits, 'an'))  // ['banana', 'mango', 'orange']
const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange']

/**
 * Filter array items based on search criteria (query)
 */
const filterItems = (arr, query) => {
  return arr.filter(el => el.toLowerCase().indexOf(query.toLowerCase()) !== -1)
}

console.log(filterItems(fruits, 'ap'))  // ['apple', 'grapes']
console.log(filterItems(fruits, 'an'))  // ['banana', 'mango', 'orange']

초기 배열에 영향(수정, 추가 및 삭제)

// Modifying each words
let words = ['spray', 'limit', 'exuberant', 'destruction', 'elite', 'present']

const modifiedWords = words.filter( (word, index, arr) => {
  arr[index+1] +=' extra'
  return word.length < 6
})

console.log(modifiedWords)
// Notice there are three words below length 6, but since they've been modified one is returned
// ["spray"]

// Appending new words
words = ['spray', 'limit', 'exuberant', 'destruction', 'elite', 'present']
const appendedWords = words.filter( (word, index, arr) => {
  arr.push('new')
  return word.length < 6
})

console.log(appendedWords)
// Only three fits the condition even though the `words` itself now has a lot more words with character length less than 6
// ["spray" ,"limit" ,"elite"]

// Deleting words
words = ['spray', 'limit', 'exuberant', 'destruction', 'elite', 'present']
const deleteWords = words.filter( (word, index, arr) => {
  arr.pop()
  return word.length < 6
})

console.log(deleteWords)
// Notice 'elite' is not even obtained as its been popped off `words` before filter can even get there
// ["spray" ,"limit"]

'NestJS' 카테고리의 다른 글

TIL | TypeScript_기본문법2  (0) 2021.10.10
TIL | TypeScript_기본 문법1  (0) 2021.10.10
TIL | Typescript_Setting_초기개발환경세팅  (0) 2021.10.07
TIL | Node_개발환경세팅  (0) 2021.10.05
TIL | Node.js_Map()  (0) 2021.10.04
Share Link
reply
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31