Reputation: 2460
I'm trying to do a .filter() method on each keyup to get back a list of objects in the following array that match the value of an input field:
var peopleArray = [
{
name: "Steve",
email: "[email protected]"
},
{
name: "Sam",
email: "[email protected]"
},
{
name: "Sarah",
email: "[email protected]"
},
{
name: "Kyle",
email: "[email protected]"
},
{
name: "Kody",
email: "[email protected]"
},
{
name: "Scarlet",
email: "[email protected]"
},
]
Here is what I'm using to search:
<input type="search" id="searchInput" placeholder="Search Activities" />
searchInput.addEventListener('keyup', function() {
searchPeople(searchInput.value);
})
function searchPeople(chars) {
//Search People and return a list of JSON objects
return //All JSON objects that matched
}
I'm new to this so I don't quite understand how to achieve this.
Upvotes: 0
Views: 74
Reputation: 14501
This will search for people based on name and email. Uppercase/lowercase doesn't matter, because it compares lowercase values to lowercase values.
filter needs to return a "truthy" value. So basically it should return anything that is not: false
, 0
, undefined
, null
, NaN
or ""
(an empty string).
match will search for a string inside of another string and returns an array of the matched value if it's found, or null if it's not found. So if match cannot find anything, the return line is essentially return null || null;
and since null
is "falsy", filter will exclude that person from the result.
function searchPeople(chars) {
peopleArray.filter(function(person) {
var name = person.name.toLocaleLowerCase();
var email = person.email.toLocaleLowerCase();
var searchTerm = chars.toLocaleLowerCase();
return name.match(searchTerm) || email.match(searchTerm);
});
}
Upvotes: 3
Reputation: 48267
If you want a simple string search, you would use filter
with indexOf
to return every string containing the input:
function searchPeople(chars) {
return people.filter(function (person) {
return person.name.indexOf(chars) > -1;
});
}
If indexOf
finds the string matching chars
, it will return a location (index) greater than -1
. This will match the filter and keep that person.
You can expand the filter predicate to check both name
and email
if you'd like:
function searchPeople(chars) {
return people.filter(function (person) {
return (person.name.indexOf(chars) > -1 || person.email.indexOf(chars) > -1);
});
}
Upvotes: 5