1

"items" array:

[
            {id:1,name:"Product 1",label:"Lorem ipsum dolor sit amet, consectetur adipiscing elit",price:25},
            {id:2,name:"Product 2",label:"Lorem ipsum dolor sit amet, consectetur adipiscing elit",price:30},
            {id:3,name:"Product 3",label:"Lorem ipsum dolor sit amet, consectetur adipiscing elit",price:50},
            {id:4,name:"Product 4",label:"Lorem ipsum dolor sit amet, consectetur adipiscing elit",price:150},
            {id:5,name:"Product 5",label:"Lorem ipsum dolor sit amet, consectetur adipiscing elit",price:10}
]

"cartItems" Array:

 [
            {id:1,qty:1},
            {id:4,qty:5}
 ]

I need to create a component for items which ID is in both arrays. I tried it:

cartItems.map(cartItem => {
   return items.map(item => {
       if (cartItem.id === item.id) {
          return <MyComponent key={cartItem.id} />
       }
   });
})

and it works. But is there any other way instead of using map twice like this?

Artem Arkhipov
  • 7,025
  • 5
  • 30
  • 52
nawkee
  • 33
  • 6

2 Answers2

1

The other way to do that:

cartItem.filter(v => (items.findIndex(x => x.id == v.id) >= 0)).map((value) => 
{
    return <MyComponent key={cartItem.id} />
})
Shahbaz
  • 178
  • 7
1

Let's make a structure that can help improve on the complexity of your approach.

We can use an object lookup such that we don't need to filter through every item in the inventory for every cart item. First, define a function to make the lookup:

const toObjectLookup = (items, keySelector) => 
    Object.fromEntries(items.map(item => [keySelector(item), item]));

and use this on our items:

const itemsById = toObjectLookup(items, item => item.id);

to give us an itemsById structure that looks like:

{
    "1": {
        "id": 1,
        "name": "Product 1",
        "label": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
        "price": 25
    },
    "2": {
        "id": 2,
        "name": "Product 2",
        "label": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
        "price": 30
    },
    // ...
}

Now, we can improve the mapping

cartItems.map(cartItem => {
    const item = itemsById[cartItem.id];
    return <MyComponent key={cartItem.id} />;
})
spender
  • 117,338
  • 33
  • 229
  • 351