
배열에서 특정 단어가 들어간 요소만 추출하거나 제외하는 작업이 필요할 경우에 사용할 수 있다.
filter에 includes, some 메소드를 이용해서 구현할 수 있다.
filter는 조건에 해당하는 요소를 새 배열로 반환한다.
includes는 true, false를 반환한다.
some은 한가지라도 참일 때 true를 반환하고 빈 배열이면 false를 반환한다.
// 배열에서 "X"가 포함된 단어 필터링
Array.filter((el) => el.includes('필터링할 단어'));
// 배열에서 "X"가 포함된 단어만 빼고 필터링
Array.filter((el) => !el.includes('제외할 단어'));
// 배열에서 [A, B]가 포함된 단어 필터링
const filteringTexts = ['A', 'B'];
Array.filter((el) => filteringTexts.some((text) => el.includes(text)));
// 배열에서 [A, B]가 포함된 단어만 빼고 필터링
const filteringTexts = ['A', 'B'];
Array.filter((el) => !filteringTexts.some((text) => el.includes(text)));
출처