Reputation: 483
I'm having trouble figuring out why this function isn't returning results if the keyword is a substring.
const string = 'cake';
const substring = 'cak';
console.log(string.includes(substring));
// returns true
But when I try to do something similar here I'm not getting the result I expect.
function filterByKeyword(array, keyword) {
return array.filter((x) =>
x.keywords
.map(function(x) {
return x.toLowerCase();
})
.includes(keyword.toLowerCase())
);
};
const array = [{
"id": 1014,
"keywords": [
"Sesame Street",
"Cake",
"Party",
"Birthday"
]
},
{
"id": 1015,
"keywords": [
"Sesame Street",
"Party",
"Birthday"
]
}
];
console.log(filterByKeyword(array, 'cak'))
// returns []
console.log(filterByKeyword(array, 'cake'))
// returns an array with the correct object
What am I doing wrong?
Upvotes: 4
Views: 1091
Reputation: 630
you are actually applying includes()
function to the array not on string that's the issue.
here I'm using reduce for this purpose.
function filterByKeyword(array, keyword) {
return array.filter((x) =>
x.keywords
.reduce(function (result ,x) {
return result + x.toLowerCase().includes(keyword.toLowerCase())
}, false)
);
};
const array = [{
"id": 1014,
"keywords": [
"Sesame Street",
"Cake",
"Party",
"Birthday"
]
},
{
"id": 1015,
"keywords": [
"Sesame Street",
"Party",
"Birthday"
]
}
];
console.log(filterByKeyword(array, 'cak'))
// returns [{...}]
console.log(filterByKeyword(array, 'cake'))
///return [{...}]
Upvotes: 1
Reputation: 207557
String includes is not the same as Array Includes. Array includes needs a full match of the index. It is not a partial match. Couple of ways to do it. The simplest is to just make the array a string and look for a match
const array = [
{
"id":1014,
"keywords":[
"Sesame Street",
"Cake",
"Party",
"Birthday"
]
},
{
"id":1015,
"keywords":[
"Sesame Street",
"Party",
"Birthday"
]
}];
function find(partial) {
return array.filter(function (obj) {
return obj.keywords.join(",").toLowerCase().includes(partial)
});
}
console.log(find('cak'));
Other option is using some()
const array = [{
"id": 1014,
"keywords": [
"Sesame Street",
"Cake",
"Party",
"Birthday"
]
},
{
"id": 1015,
"keywords": [
"Sesame Street",
"Party",
"Birthday"
]
}
];
function find(partial) {
return array.filter(function(obj) {
return obj.keywords.some(function(txt) {
return txt.toLowerCase().includes(partial);
})
});
}
console.log(find('cak'));
Upvotes: 1
Reputation: 89527
You can use Array#some
to check if any of the strings in the array includes the keyword.
function filterByKeyword(array, keyword) {
return array.filter((x) =>
x.keywords.some(w=>w.toLowerCase().includes(keyword.toLowerCase()))
);
};
const array = [
{
"id":1014,
"keywords":[
"Sesame Street",
"Cake",
"Party",
"Birthday"
]
},
{
"id":1015,
"keywords":[
"Sesame Street",
"Party",
"Birthday"
]
}];
console.log(filterByKeyword(array, 'cak'))
Upvotes: 4