Victor
Victor

Reputation: 835

React, render array in different divs, depending on the condition

For example we have the array of objects;

let arr = [
    {id: 10, name: 'hello10'}, 
    {id: 10, name: 'hello10'},
    {id: 13, name: 'hello13'},
    {id: 16, name: 'hello16'},
    {id: 17, name: 'hello17'},
    {id: 17, name: 'hello17'},
    {id: 17, name: 'hello17'}
];

After I will make array map how can get the structure below in React? And this should be generic, because we don't know about id's we will get.

<div>
    <p>hello10</p>
    <p>hello10</p>
</div>
<div>
    <p>hello13</p>
</div>
<div>
    <p>hello16</p>
</div>
<div>
    <p>hello17</p>
    <p>hello17</p>
    <p>hello17</p>
</div>

Upvotes: 2

Views: 492

Answers (3)

You can try this

let dict = {};
let idArr = [];

const len = arr.length;

//We are grouping our data by id
arr.map((ar) =< {
    if(!dict[ar.id]){
        dict[arr[i].id] = [];
        idArr.push(arr[i].id);
    }
    dict[arr[i].id].push(arr[i]);
});

// Now we will generate the output
idArr.map((id) => {
    return <div>{dict[id].map((elem) => <p>{elem}</p>)}</div>
});

Upvotes: 2

hsz
hsz

Reputation: 152266

Try with grouping your data by id first:

Object.values(
  arr.reduce((acc, item) => ({
    ...acc,
    [item.id]: (acc[item.id] || []).concat(item),
  }), {})
).map(group => (
  <div>
    {group.map(item => (
      <p>{item.name}</p>
    ))}
  </div>
))

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386680

You could group in advance and then render the result with the tags.

var array = [ { id: 10, name: 'hello10' }, { id: 10, name: 'hello10' }, { id: 13, name: 'hello13' }, { id: 16, name: 'hello16' }, { id: 17, name: 'hello17' }, { id: 17, name: 'hello17' }, { id: 17, name: 'hello17' }],
    grouped = array.reduce((r, o, i, a) => {
        if (o.id === (a[i - 1] && a[i - 1].id)) {
            r[r.length - 1].push(o);
        } else {
            r.push([o]);
        }
        return r;
    }, []);
    
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 3

Related Questions