Hi there I am working on the marvel Api, i have managed to extract data but now i want to create a search function whereby only those characters from the api are returned that include my search term, i have been playing around with it for a bit but not been successful yet, any ideas please help.
this is returning all the api results and then an empty array, i want to show only api results that contain my my search input so for exapmple if i search ‘men’ then i want a list of all characters that contain men
Opinionated I know, but the first thing I would do would be rename that function and call it something like getMatchingCharacters or getMatchingChars. ‘searchQuery’ is a bit vague to me, and doesn’t tell me what the function does.
I would change it so that it took two arguments, a search term and the characters array. That way you aren’t relying on globals, and hunting through your code to find where these variables originate from.
The other benefit is that you are able to test it as a standalone function.
function getMatchingChars(searchTerm, characters) {
const searchToLower = searchTerm.trim().toLowerCase();
// flatMap might be a better option here
// this will return an array of only the matching characters
const filteredResult = characters.flatMap((character) => {
const characterName = character.name.toLowerCase();
if (characterName.includes(searchTerm)) {
return characterName;
}
return []; // this will be discarded by flatMap
});
// console.log(filteredResult)
}
It looks like you want a mixture of filter and map to me, so I have swapped out what you have for flatMap
thanks for that i have another issue in that when ever i close my visual studio code then open my project up it does not run, i have to keep creating a vite project each time which cant be correct way of doing it, what am i doing wrong anyone know? im sure i figured this issue out a few months back but iv had a break from coding now forgot
You have a misunderatnding of how filter works. Filter relies on a function (predicate) returning true or false. If the function returns true the item in the array is kept, if the function returns false the item in the array is discarded.
MDN
callbackFn
A function to execute for each element in the array. It should return a truthy value to keep the element in the resulting array, and a falsy value otherwise.