How can I group an array of objects ? Is it possible to use reduce in the following case?
Ex: I need to group id and name if its same need to append data alone into one field.
[{
data: ["Sriram Krishnan", 1440]
id: "CHARSUR"
name: "CHARSUR"
},
{
data: ["shaleesh ", 2955]
id: "Timesheet"
name: "Timesheet"
},
{
data:["Balachander ", 3720]
id: "CHARSUR"
name: "CHARSUR"
},
{
data: ["Sriram Krishnan", 720]
id: "Aroscop"
name: "Aroscop"
},
{
data: ["Karthik ", 540]
id: "Timesheet"
name: "Timesheet"
},
{
data: ["Shaju Murugan", 420]
id: "CHARSUR"
name: "CHARSUR"
}]
Expected result: I need the grouped result (data) to be append in array of array.
[{
data: [["Sriram Krishnan", 1440],["Balachander ", 3720],["Shaju Murugan", 420]]
id: "CHARSUR"
name: "CHARSUR"
},
{
data: [["shaleesh ", 2955],["Karthik ", 540]]
id: "Timesheet"
name: "Timesheet"
},
{
data: ["Sriram Krishnan", 720]
id: "Aroscop"
name: "Aroscop"
}]
I'M forming data in such a way to use in highcharts pie chart.
In your source data, please make sure that the object fields are separated by comma:
src = [
{
data: ['Sriram Krishnan', 1440],
id: 'CHARSUR',
name: 'CHARSUR',
},
{
data: ['shaleesh ', 2955],
id: 'Timesheet',
name: 'Timesheet',
},
{
data: ['Balachander ', 3720],
id: 'CHARSUR',
name: 'CHARSUR',
},
{
data: ['Sriram Krishnan', 720],
id: 'Aroscop',
name: 'Aroscop',
},
{
data: ['Karthik ', 540],
id: 'Timesheet',
name: 'Timesheet',
},
{
data: ['Shaju Murugan', 420],
id: 'CHARSUR',
name: 'CHARSUR',
}];
This JavaScript code will yield the expected grouped results:
let dst = [];
function getRecordInDst(srcRecord) {
for (let dstRecord of dst) {
if (dstRecord.id === srcRecord.id) return dstRecord;
}
let newRecord = {id: srcRecord.id, name: srcRecord.name, data: []};
dst.push(newRecord);
return newRecord;
}
for (let record of src) {
getRecordInDst(record).data.push(record.data);
}