Skip to content

Instantly share code, notes, and snippets.

@kingisaac95
Last active August 5, 2021 13:54
Show Gist options
  • Save kingisaac95/b97a0db96c23da962a62e511738b70af to your computer and use it in GitHub Desktop.
Save kingisaac95/b97a0db96c23da962a62e511738b70af to your computer and use it in GitHub Desktop.
A simple algorithm to search through a contact list; where contact list is an array with first and last names spaced out.
const sampleData = ['tom harry', 'dike harry', 'girl guy', 'boo baa'];
/**
* use first/last name to create regex pattern
* if no last name return first name pattern
*/
const getSearchPattern = (terms, index) =>
new RegExp(".*" + (terms[index] ? terms[index] : terms[0]) + ".*");
const searchUsers = (searchTerm) => {
const searchTerms = searchTerm.split(' ');
const fNamePattern = getSearchPattern(searchTerms, 0);
const lNamePattern = getSearchPattern(searchTerms, 1);
const results = sampleData.filter((each) =>
fNamePattern.test(each) || lNamePattern.test(each));
console.log(results);
}
// test
searchUsers('dik tom');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment