Array.prototype.filter()

김혁중·2022년 3월 11일
0

JavaScript

목록 보기
10/23

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

구문

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

구현1

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

function callback(element) {
  // console.log(element)
  if(element.length > 6) {
    return true
  } else {
    return false
  }
}

newWords = words.filter(callback)
console.log(newWords) // ['exuberant', 'destruction', 'present']

구현2

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

function callback(element) {
  // 간소화
  return element.length > 6
}

newWords = words.filter(callback)
console.log(newWords) // ['exuberant', 'destruction', 'present']

구현3

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

// 콜백함수 자체를 인자로
newWords = words.filter(element => element.length > 6)
console.log(newWords) // ['exuberant', 'destruction', 'present']
profile
Digital Artist가 되고 싶은 초보 개발자

0개의 댓글