[23.01.02] JS map, filter, find 함수

희승·2023년 1월 2일

TIL

목록 보기
11/33
  • map
    • 배열 순회하면서 요소마다 콜백함수 적용하고 새로운 배열로 리턴
    • 배열.map((요소, 인덱스, 배열) ⇒ { return 요소 });
    • cf. 배열.reduce((누적값, 현재값, 인덱스, 요소) ⇒ { return 결과 }, 초기값);
  • filter
    • map, filter 비교
      • 공통점 : 기존 배열은 건드리지 않으면서 요소 순회하면서 새로운 배열 리턴
      • 차이점 : map은 콜백함수가 적용된 새 요소 반환, filter는 조건문을 만족한 요소만 반환
    • 예시
      const words = ['limit', 'exuberant', 'destruction', 'present'];
      const result = words.filter(word => word.length > 6);
      console.log(result);
      // Array ["exuberant", "destruction", "present"]
  • find
    • 배열 요소 중에서 어떤 조건에 맞는 첫번째 요소만 골라내고 싶을 때 사용
    • array.find((element, index, array) ⇒ {…}); array.find(callbackFn, thisArg); array.find(function(element, index, array) {…}, thisArg);
    • 원본 배열 변형 안함
    • 어떤 값의 인덱스를 찾고 싶으면 indexOf()를 쓰는게 나음 어떤 값의 존재 유무를 알고 싶으면 includes()를 쓰는게 나음 콜백함수 조건에 맞는 요소가 있는지 없는지 알고 싶으면 some()을 쓰는게 나음

0개의 댓글