0

I'm trying to filter down results from a large array of objects. Basically I have an input and I want to filter down the results when the input matches one or part of the keywords.


export default [
    {
       "id":1014,
       "item":19021,
       "name":"name 1",
       "description":"",
       "image":"http://images.jpg",
       "keywords":[
          "Cake",
          "Party",
          "Birthday"
       ],
    },
    {
       "id":1015,
       "item":19023,
       "name":"name 22",
       "description":"",
       "image":"http://images.jpg",
       "keywords":[
          "NHL",
          "Party"
       ],
    },
    {
       "id":1042,
       "item":19011,
       "name":"name 3",
       "description":null,
       "image":"http://images.jpg",
       "keywords":[
          "Florida Panthers",
          "NHL"
       ],
    },

Expected result if input is 'NHL':

    {
       "id":1015,
       "item":19023,
       "name":"name 20",
       "description":"",
       "image":"http://images.jpg",
       "keywords":[
          "NHL",
          "Party"
       ],
    },
    {
       "id":1042,
       "item":19011,
       "name":"NHL® Florida Panthers® Slap Shot Cake",
       "description":null,
       "image":"http://images.jpg",
       "keywords":[
          "Florida Panthers",
          "NHL"
       ],
    }

I tried something like this:

myArray.filter(x => x.keywords === searchFilter)

But it doesn't search through the keyword array.

So basically I need something like this:

myArray.filter(x => x.keywords[loop through all indexes] === searchFilter)

What's the best way to do this?

2
  • 1
    Use includes along with filter to check if the item present in the keywords:arr.filter(o=>o.keywords.includes('NHL')) Commented Mar 5, 2021 at 18:57
  • You've got it. You can use array.includes(keyword) Commented Mar 5, 2021 at 18:57

1 Answer 1

2

Check if the nested array .includes the string you're looking for:

const myArray=[{id:1014,item:19021,name:"name 1",description:"",image:"http://images.jpg",keywords:["Cake","Party","Birthday"]},{id:1015,item:19023,name:"name 22",description:"",image:"http://images.jpg",keywords:["NHL","Party"]},{id:1042,item:19011,name:"name 3",description:null,image:"http://images.jpg",keywords:["Florida Panthers","NHL"]}];

const filtered = myArray.filter(item => item.keywords.includes('NHL'));
console.log(filtered);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.