본문 바로가기
💻CODING/javascript

[js] 단어 filtering 다중 단어 filtering (ft. includes, some)

by 코딩하는 갓디노 2022. 2. 17.

[js] 단어 filtering 다중 단어 filtering (ft. includes, some)

 

원하는 단어 또는 다중 단어
한번에 필터링하기 입니다.

 

  • 배열 안에서 특정 단어 또는 text가 들어간 요소만 추출하거나
    제외시키는 작업이 필요할 경우 사용합니다. 
  • filtering에 자바스크립트의 includes와 some 메소드를 사용하여 구현합니다.
  • includes는 true, false를 반환합니다.
  • some은 한가지라도 참일 때 true를 반환하고 빈 배열이면 false를 반환합니다.

 

단어 필터링

배열 안에 "AA"가 들어가는 단어를 필터링할 때 

Array.filter(el => el.includes('AA'))
Array.filter(el => el.includes('AA')).map(el => <div>{el}</div>)

 

배열 안에 "AA"가 들어가는 단어만 빼고 필터링 할때 

Array.filter(el => !el.includes('AA')).map(el => <div>{el}</div>)

 

단어 필터링 예제

let array = [
  'Lorem Ipsum is simply dummy text of the printing and typesetting industry.',
  'Lorem Ipsum has been the industry',
  'It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.',
  'It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages',
  'and more recently with desktop publishing software like Aldus PageMaker including versions'
]

const result = array.filter(el => el.includes('Lorem'))
console.log(result)
//(3) ['Lorem Ipsum is simply dummy text of the printing and typesetting industry.', 
//'Lorem Ipsum has been the industry', 
//'It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages']

 

다중 단어 필터링

배열 안에 [AA, BB] 가 들어가는 단어를 필터링할 때 

const filteringTexts = ['AA', 'BB']
Array.filter(el => filteringTexts.some(text => el.includes(text)))

 

배열 안에 [AA, BB] 가 들어가는 단어만 빼고 필터링할 때 

const filteringTexts = ['AA', 'BB']
Array.filter(el => !filteringTexts.some(text => el.includes(text)))

 

다중 단어 필터링 예제

let array = [
  'Lorem Ipsum is simply dummy text of the printing and typesetting industry.',
  'Lorem Ipsum has been the industry',
  'It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.',
  'It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages',
  'and more recently with desktop publishing software like Aldus PageMaker including versions'
]

const filteringTexts = ['versions', 'industry']

const result = array.filter(el => filteringTexts.some(v => el.includes(v)))
console.log(result)
//(3) ['Lorem Ipsum is simply dummy text of the printing and typesetting industry.', 
//'Lorem Ipsum has been the industry', 
//'and more recently with desktop publishing software like Aldus PageMaker including versions']
반응형

댓글