[React] filter() 함수

후니·2023년 8월 22일

React

목록 보기
3/12

📖 filter()란?

Javascript 배열의 내장 함수
주어진 함수의 테스트를 통과하는 모든 요소를 모아(true면 요소 유지, false면 버림) 새로운 배열로 반환
callback 함수는 호출되는 배열을 변화시키지 않음

callback 함수는 3개의 인수와 함께 호출

  • 처리할 현재(대상) 요소값
  • 처리할 현재(대상) 요소의 인덱스
  • filter를 호출한 배열 객체(=순회되는 배열 객체)

사용법

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

const result = words.filter(word => word.length > 6);

console.log(result); // ["exuberant", "destruction", "present"]

[ 검색 예시 1 ]

notes = {notes.filter((note) =>
	note.text.toLowerCase().includes(searchText)
)}

notes 배열에 들어있는 note.text가 searchText를 포함하고 있으면 notes 배열 구성

[ 검색 예시 2 ]

const deleteNote = (id) => {
	const newNotes = notes.filter((note) => note.id !== id);
    setNotes(newNotes);
}

notes 배열에서 note.id가 파라미터로 일치하지 않는 원소만 추출해서 새로운 배열을 만듬 = note.id가 id인 것을 제거

출처 : https://velog.io/@suhado/React-filter%ED%95%A8%EC%88%98

profile
Developer

0개의 댓글