CristalT
1/17/2019 - 7:59 PM

Two ways to filter an array making a flexible searching

const heros = [
    { label: 'Batman' },
    { label: 'Iron Man' },
    { label: 'Superman' },
    { label: 'Green Lantern' },
    { label: 'Cat Woman' },
    { label: 'Supergirl' },
    { label: 'Aquaman' }
]

const terms = 'Man Super' // unordered terms for searching

const search = terms.toLowerCase().split(' ')
console.log(search)

// Way One
const resultsOne = []

heros.forEach(item => {
    if (search.every(word => item.label.toLowerCase().search(word) !== -1)) {
        resultsOne.push(item)
    }
})
console.log(resultsOne)

// Way Two
const resultsTwo = heros.filter(item => search.every(word => item.label.toLowerCase().indexOf(word) !== -1))
console.log(resultsTwo)