.filter for specific tag in array

My array:

{
  "items": [{
    "url": "XXX",
    "title": "XXX",
    "tags": [
      "One",
      "Two"
    ]
  }]
}

I am trying to filter out and return items only where tags has "Two"

const loadArticles = async () => {
fetch(mediumRssFeed, { headers: { Accept: "application/json" } })
.then((res) => res.json())
.then((data) => data.items.filter((item) => ???))
.then((newArticles) => newArticles.slice(0, MAX_ARTICLES))
.then((articles) => setArticles(articles))
.catch((error) => console.log(error));
};

I assume it is this line:

.then((data) => data.items.filter((item) => ???))

How do I revise so that it only return those items with a tag of "Two"?

>Solution :

You can use the Array.prototype.filter() method to filter out items that do not have the tag "Two". You can use the Array.prototype.includes() method to check if the tags array includes "Two".

You can revise the line like this:

.then((data) => data.items.filter((item) =>
item.tags.includes("Two")))

This filters the items array and only keeps the items that have "Two" in their tags array.

Leave a Reply