0

I have this nested map that kind render slow after redirection I tried to map only the group and it was really fast, any idea how to get rid of this nesting yet achieve the same results? also could calling the function inside of return causing this dip.....

itemSet =  [
      { id: 1, group: 'A', item : 'someitem' },
      { id: 2, group: 'A',  item : 'someitem' },
      { id: 3, group: 'B',  item : 'someitem' },
      { id: 4, group: 'B', item : 'someitem' },
    ]

const groupItems = (items) =>
  items.reduce((group, items) => {
    if (!group[items.group]) {
      group[items.group] = [];
    }
    group[items.group].push(items);
    return group;
  }, {});

const items = (item) =>
    Object.entries(groupItems(item)).map(([group, items]) => (
      <React.Fragment>
        <group name={group} />
        {items.map((item) => (
          <item
            key={item.id}
            id={item.id}
            item={item.item}
          />
        ))}
      </React.Fragment>
    ));
  return (
    <MuiThemeProvider theme={themeDark}>
      <AppBar />
      <CssBaseline />
      {items(itemSet)}
    </MuiThemeProvider>
  );

1 Answer 1

2

I believe your usecase is to render the array of array grouped by group. You will have to use the nested loops but you're missing key attribute in the first map. Try adding key there in the React.Fragment.

const items = (item) =>
    Object.entries(groupItems(item)).map(([group, items]) => (
      <React.Fragment key={group}>
        <group name={group} />
        {items.map((item) => (
          <item
            key={item.id}
            id={item.id}
            item={item.item}
          />
        ))}
      </React.Fragment>
    ));
  return (
    <MuiThemeProvider theme={themeDark}>
      <AppBar />
      <CssBaseline />
      {items(itemSet)}
    </MuiThemeProvider>
  );

Working example on codesandbox

Sign up to request clarification or add additional context in comments.

4 Comments

you think this is causing the dip ? tbh i tried it kind of improved...
Yep, That's one reason and there is one more. You're not using 2 loops but 3 including the Object.entries. Can put a working codesandbox example. I can check and help you there with a number of loops.
link kinda similar
Updated the example. codesandbox.io/s/ancient-dust-uxq5c?file=/index.js Not a fan of for...in but that is reducing one loop in here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.