J
J
JordanBelford2021-05-02 09:57:12
React
JordanBelford, 2021-05-02 09:57:12

How to group components by parameter?

Hello! Faced such a problem, there is an object "number", I iterate over it using map

const numbers = props.mainPage.room.map(item => 
<NumberRoom key={item.id} number={item.number} storey={item.storey} state={item.state}/>);

it is necessary to make a grouping by the "storey" field, I broke my whole head, how can I implement this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-05-02
@JordanBelford

const grouped = props.mainPage.room.reduce((acc, n) => (
  (acc[n.storey] ??= []).push(n),
  acc
), {});

{Object.entries(grouped).map(([ groupName, group ]) => (
  <div className="group" key={groupName}>
    <h3>{groupName}</h3>
    {group.map(n => <NumberRoom key={n.id} {...n} />)}
  </div>
))}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question