includes() not returning true for substring

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?

Answer

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'))

Leave a Reply

Your email address will not be published. Required fields are marked *