简体   繁体   中英

Javascript How to Filter Array By Parameter

I have an array of JSON objects ("posts") in which each object contains an array of tags (strings). I want to filter the posts by passing in a tag. Such that for example, if I have 10 posts and 2 of them are tagged as "news" then I return the 2 post objects with that tag.

Here's what I've tried:

const filteredData = posts.filter(((post, tag) =>
      post.tags.filter((t, tag) => t == tag)
    ));

The above code does not work; it acts like every post is valid when that's not true. My guess is that each "tag" is a new variable and does not get passed down properly, since that's what VS Code seems to indicate from the color highlighting.

I cannot figure out the proper syntax for this problem. I am sure this is super simple though.

This site explains how the filter method works, but it doesn't explain how to pass in a parameter. It shows an example with a hard-coded number. In my case, I need to pass in the tag parameter so that I can check against a given tag.

Every other question related to this on Stack Overflow I've found is way more complicated than what I'm trying to do and does not clearly explain how the syntax works. Any help is appreciated.

You can access outside variables from within the function.

const tagToFilter = "..."

const filteredData = posts.filter((post) =>
  post.tags.includes(tagToFilter)
);

Note that I switched the inside function to use .includes() . If you needed to use a function for that, you should use .some() instead of .filter() (for the inside function).

filter need a return boolean, but u just return a new array, u can use.some() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

it should be like this

const filteredData = posts.filter(((post, tag) =>
  post.tags.some((t, tag) => t === tag)
));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM