Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React double map and filter

I have data coming from an API that provides an object with a year. I’m creating headings with possible years, and then I’d like to display the data of the object if it matches that year. There can be multiple objects that match the same year.

What I’m doing currently, but with no avail:

Simplified example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export default function App() {
  const years = [2020, 2019, 2018];
  const data = [{ year: 2019, test: "test" }];

  return (
    <div>
      {years.map((year) => (
        <h1>{year}</h1>
        {data.map(d => (
          <div>{d}</div>
        ))}
      ))}
    </div>
  );
}

This doesnt display anything. What could I be missing? Should I filter instead of check for a condition? The code doesn’t seem to loop inside a loop (map inside a map). Should I be able to do this, considering the syntax, as this returns:

Unexpected token, expected "," (11:8)

>Solution :

{years.map(year => {
return div key="key" h1 {year} h1 {data.filter(el=>el.year === year).map(el2 => h2 {el2} h2)} div}

better make it into a function tho

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading