1

I'm trying to allow my user to enter a search term and then return the strings in the array that match all names they entered. So if they typed clinton here, it would find all the clintons, but if they searched hillary clinton, leaving out the rodham middle name, it would return hillary but not bill or chelsea.

const array = ['hillary rodham clinton', 'bill clinton', 'chealsea clinton', 'louise penny', 'amanda litman']

const searchTerm1 = 'hillary clinton' // should return hillary rodham clinton
const searchTerm2 = 'clinton' // should return hillary rodham clinton, bill clinton, chelsea clinton
const searchTerm3 = 'hillary' // should return hillary rodham clinton

2 Answers 2

1

Assuming your search terms will always be separated by a single space, you can do something like this:

const array = ['hillary rodham clinton', 'bill clinton', 'chealsea clinton', 'louise penny', 'amanda litman']

const searchTerm1 = 'hillary clinton' // should return hillary rodham clinton
const searchTerm2 = 'clinton' // should return hillary rodham clinton, bill clinton, chelsea clinton
const searchTerm3 = 'hillary' // should return hillary rodham clinton

let find = (term) => array.filter(item => term.split(' ').every(r => item.split(' ').includes(r)))

console.log(find(searchTerm1))
console.log(find(searchTerm2))
console.log(find(searchTerm3))

Sign up to request clarification or add additional context in comments.

Comments

1

You can use this function to search.

function search(searchTerm, array) {
        const words = searchTerm.split(" ");
        let tmpArray = array;
        for (let i = 0; i < words.length; i++) {
            tmpArray = tmpArray.filter(obj => obj.indexOf(words[i]) >= 0);
        }
            
        return tmpArray;
}

const newArray1 = search(searchTerm1, array);
const newArray2 = search(searchTerm2, array);
const newArray3 = search(searchTerm3, array);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.