Home > Net >  How to avoid nested maps loops while rendering JSX in ReactJS
How to avoid nested maps loops while rendering JSX in ReactJS

Time:07-24

I have recently started creating a react online menu project and I encountered a situation where I had to use nested map loops to render an array of array. Please find the code below for the rendering that I have written. Below that is the data variable being used to render this information. This algorithm, though it does the job and in most real life applications won't cause the user's system to hang, but it is still O(n^2) complexity. How can this nested loop be avoided while still rendering the correct style and information?

The code I have used to render:

<div className="container-fluid">
    <div className="rajat-menu-wrapper">
        {items.map(item => 
            <div key={item.title}>
                <h1 className="rajat-menu-category-heading"><span>{item.title}</span></h1>
                {item.items.map(foodItem => <FoodCard key={foodItem.name} data={foodItem}/>)}
            </div>)}
    </div>
</div>

Below is the data:

const menuData = [
    {
        title: 'Pizzas',
        items: [
            {
                name: 'Onion Pizza',
                desc: 'Enjoy the delicious treat of onions with extra cheese over a classic hand tossed dough.'
            },
            {
                name: 'Capsicum Pizza',
                desc: 'Enjoy the delicious treat of capsicums with extra cheese over a classic hand tossed dough.'
            },
            {
                name: 'Tomato Pizza',
                desc: 'Enjoy the delicious treat of tomatoes with extra cheese over a classic hand tossed dough.'
            },
            {
                name: 'Olive Pizza',
                desc: 'Enjoy the delicious treat of olives with extra cheese over a classic hand tossed dough.'
            },
            {
                name: 'Golden Corn Pizza',
                desc: 'Enjoy the delicious treat of corns with extra cheese over a classic hand tossed dough.'
            }
        ]
    }
];

CodePudding user response:

Reducing time complexity is necessary where there exist iterations that have no contribution to the end result. In your case, every iteration is necessary to display your data. So you shouldn't worry about the time complexity of that. Hope this helps.

CodePudding user response:

This algorithm [...] is still O(n^2) complexity.

No, if

  • Related