mercredi 13 juin 2018

Javascript filter an array with another array of elements

I want to implement a tag filter for a search and get an array of entries (variable: entries) like this with many entries:

"entries":[
      {
         "id":1,
         "details":"text",
         "tags":[
            {
               "id":9,
               "label":"Label9"
            },
            {
               "id":6,
               "label":"Label6"
            },
         ],
         "date":"Mar 8, 2018 2:45:30 PM"
      }]

I want to filter this array with another array of tags (variable: tags) like this:

"tags":[
            {
               "id":6,
               "label":"Label6"
            }
         ]

I wrote this code but something is wrong. It compares the id of each tag.

function containSearchTag(tags) {
    return entries.filter(function (el) {
        for(let i = 0; i < el.tags.length; i++) {
            for(let j = 0; j < tags.length; j++) {
                return el.tags[i].id === tags[j].id;
            }
        }
    });
}

At the end I need an array of those entries which contain all tags in the tags array.




Aucun commentaire:

Enregistrer un commentaire