0

I have array of items in the following structure.

[{column: 1, name: 'one'}, {column: 2, name: 'Two'},{column: 2, name: 'Three'},{column: 3, name: 'Four'}]

Need to loop through the array and items with same column value should be wrapped in single parent. Like,

<div class="parent">
    One
</div>
<div class="parent">
    <div>Two</div>
    <div>Three</div>
</div>
<div class="parent">
    Four
</div>

As you can see the second parent element have two child, because they have same column value "2".

2 Answers 2

1

Aggregate array based on column and then generate data based on aggregated value.

const array = [{column: 1, name: 'one'}, {column: 2, name: 'Two'},{column: 2, name: 'Three'},{column: 3, name: 'Four'}]

const aggregatedArray = array.reduce((agg, {column, name})=>{
  if(!Array.isArray(agg[column)){
    agg[volumn] = []
  }
  agg[column].push(name)
  return agg
}, {})

Object.entries().map([key, value]=><div className="parent">
  {value.map(v=><div>{v}</div>)}
</div>)

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

1 Comment

there is a couple of syntax errors: agg[column] missing ], ([key, value]) missing (), ...
0

const arr0 = [
  {column: 1, name: 'one'},
  {column: 2, name: 'Two'},
  {column: 2, name: 'Three'},
  {column: 3, name: 'Four'},
];
/* convert Array<{ column: number, name: string }>
 * to Array<Array<string>>
 * 
 * convert(arr0) return [['one'], ['two', 'three'], ['four']]
 */
const convert = arr => arr.reduce((acc, { column, name }) => {
  const index = column - 1;

  if (!acc[index]) {
    acc[index] = [name];
  } else {
    acc[index].push(name);
  }
  
  return acc;
}, []);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.