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
CodePudding user response:
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))
CodePudding user response:
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);