I am using the javascript includes()
method to filter an array of object that looks like this;
const names = [
{name: 'Rose-mary Thompson', age: 30},
{name: 'Rose mary Samuel', age: 30},
{name: 'John-Doe Jackson', age: 30},
{name: 'John Doe Philips', age: 30},
]
if I search for 'Rose mary', I want the result to also include 'Rose-mary'. I don't want the user to have to type hyphen(-) before the names with - come out in the search result.
This is my code;
let searchQuery = 'Rose mary'
let filteredResults = []
const searchItems = () => {
if (searchQuery.length > 1) {
const results = names.filter((name) => {
return name.name.toLowerCase().includes(searchQuery.toLowerCase());
});
filteredResults = results
}
}
Please how do I achieve this?
CodePudding user response:
includes
will only find an exact match. Since you're already adjusting each string as you search, you could "normalize" both searchQuery
and name
to be lower case with -
converted to space:
const searchItems = () => {
if (searchQuery.length > 1) {
const adjustedQuery = searchQuery.toLowerCase().replace(/-/g, " ");
const results = names.filter((name) => {
return name.name
.toLowerCase()
.replace(/-/g, " ")
.includes(adjustedQuery);
});
filteredResults = results;
}
};
const names = [
{ name: "Rose-mary Thompson", age: 30 },
{ name: "Rose mary Samuel", age: 30 },
{ name: "John-Doe Jackson", age: 30 },
{ name: "John Doe Philips", age: 30 },
];
let searchQuery = "Rose mary";
let filteredResults = [];
const searchItems = () => {
if (searchQuery.length > 1) {
const adjustedQuery = searchQuery.toLowerCase().replace(/-/g, " ");
const results = names.filter((name) => {
return name.name
.toLowerCase()
.replace(/-/g, " ")
.includes(adjustedQuery);
});
filteredResults = results;
}
};
searchItems();
console.log(filteredResults);
Side note: I'd also make names
and searchQuery
parameters to the function, and have it return the results:
const names = [
{ name: "Rose-mary Thompson", age: 30 },
{ name: "Rose mary Samuel", age: 30 },
{ name: "John-Doe Jackson", age: 30 },
{ name: "John Doe Philips", age: 30 },
];
const searchItems = (names, searchQuery) => {
if (searchQuery.length > 1) {
const adjustedQuery = searchQuery.toLowerCase().replace(/-/g, " ");
const results = names.filter((name) => {
return name.name
.toLowerCase()
.replace(/-/g, " ")
.includes(adjustedQuery);
});
return results;
}
return names; // Or whatever you want when there's no query
};
console.log(searchItems(names, "Rose mary"));