I have an array of objects like below.
var array1 = [
{ col1: 'ABC1+R2', col2: 'ABC', col3: 'R20'},
{ col1: 'ABC1+R3', col2: 'ABC', col3: 'R20'},
{ col1: 'ABC1+R2', col2: 'ABC', col3: 'R301'},
{ col1: 'ABC1+R3', col2: 'ABC', col3: 'R301'},
{ col1: 'CDE2+R4', col2: 'CDE', col3: 'R20'},
{ col1: 'CDE2+R5', col2: 'CDE', col3: 'R30'},
{ col1: 'RED4+R3', col2: 'RED', col3: 'D20'},
{ col1: 'GTR5+R2', col2: 'GTR', col3: 'R20'}];
var result = array1.reduce(function(r, a) {
r[a.col2] = r[a.col2] || [];
r[a.col2].push(a);
return r;
}, Object.create(null));
console.log(result);
I tried the above script, but couldn't achieve. somewhere i did mistake.
i want the output like below need to group col1 and col3 based on col2. Thanks in advance.
var res = [
{
"col1": [{text1: "ABC1+R2"},{text1: "ABC1+R"}],
"col2": "ABC",
"col3": [{text2: "R20"},{text2: "R301"}],
},
{
"col1": [{text1: "CDE2+R4"},{text1: "CDE2+R5"}],
"col2": "CDE",
"col3": [{text2: "R20"},{text2: "R30"}],
},
{
"col1": "RED4+R5",
"col2": "RED",
"col3": "D20"
},
{
"col1": "GRT3",
"col2": "ED",
"col3": "R20"
}
];
console.log(res);
col1andcol2to array all the time?