-1

I have a data of students and their marks in various subjects as an array of objects. I need to club the data as a single object when the name of the two objects are same so that I will have only one record for each student. An example of the sample data:

{
    data: [{
        "name: xxx,
    "createdDate:10/01/2018,
    subj1: 20,
        subj2: 40
    },
    {
        "name: xxx,
    "createdDate:10/11/2017,
    subj1: 40,
        subj2: 70
    },
    {
        "name: yyy,
    "createdDate:10/01/2018,
    subj1: 20,
        subj2: 40
    }]
}

and I need to convert it something like this:

{
    data: [
        {
            name: xxx,
            subj1: [20, 40],
            subj2: [70, 40]
        },
        {
            name: yyy,
            subj1: [20],
            subj2: [40]
        }
    ]
}

How can I achieve this in node js. Only through looping I can do or is there an easy way I can achieve this by using libraries like lodash,underscore js.

Waleed Iqbal
  • 1,308
  • 19
  • 35
Gopi Nath
  • 413
  • 3
  • 7
  • 21
  • Possible duplicate of [Group array items using object](https://stackoverflow.com/questions/31688459/group-array-items-using-object) – Rajesh Jan 25 '18 at 07:16

1 Answers1

1

You can use map and reduce to do something like this perhaps:

let sampleData = {
data:[{
name: "xxx",
createdDate:10/01/2018,
subj1:20,
subj2:40
},
{
name: "xxx",
createdDate:10/11/2017,
subj1:40,
subj2:70
},
{
name: "yyy",
createdDate:10/01/2018,
subj1:20,
subj2:40
}]
};

let sorted = sampleData.data.sort((element1, element2) => {
 return element1.name <= element2.name ? -1 : 1
}).reduce((accumulator, currentValue, currentIndex, array) => {
   if (accumulator.data.length == 0){
   accumulator.data.push({name:currentValue.name, subj1:[currentValue.subj1], subj2:[currentValue.subj2]});
    return accumulator;
  } else {
    if (accumulator.data[accumulator.data.length - 1].name == currentValue.name){
     accumulator.data[accumulator.data.length - 1].subj1.push(currentValue.subj1);
      accumulator.data[accumulator.data.length - 1].subj2.push(currentValue.subj2);
    } else {
     accumulator.data.push({name:currentValue.name, subj1:[currentValue.subj1], subj2:[currentValue.subj2]});
    }
    return accumulator;
  }
}, {data:[]})

console.log(sorted)
BlackBeard
  • 10,246
  • 7
  • 52
  • 62