matmik
matmik

Reputation: 670

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:

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)

Upvotes: 0

Views: 76

Answers (2)

ColdDarkness
ColdDarkness

Reputation: 331

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

Upvotes: 3

mahdikmg
mahdikmg

Reputation: 908

Try this:

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

If you want to also have a condition inside your map function, use this:

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

Upvotes: 2

Related Questions