[React] filter()함수

SUHA JEONG·2021년 9월 29일
3

[keyword]
filter함수, 검색, 삭제


✔️ filter() 메서드: 자바스크립트 배열의 내장 함수

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

callback 함수는 3개의 인수와 함께 호출됨.
1. 처리할 현재(대상) 요소값
2. 처리할 현재(대상) 요소의 인덱스
3. filter을 호출한 배열 객체(=순회되는 배열 객체)


기본 사용법

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

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

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

1) filter()을 활용한 검색 예시 ⬇️

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

notes배열에 들어있는 note.textsearchText를 포함하고 있으면 notes배열로 구성


2) filter()을 활용한 삭제 예시 ⬇️

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

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


참고자료:
[1]https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
[2]https://dongmin-jang.medium.com/javascript-15%EA%B0%80%EC%A7%80-%EC%9C%A0%EC%9A%A9%ED%95%9C-map-reduce-filter-bfbc74f0debd
[3]https://react.vlpt.us/basic/14-array-remove.html

0개의 댓글