0

I have an array which looks like:

var data = [
  {
    student: "sam",
    English: 80,
    Std: 8
  },
  {
    student: "sam",
    Maths: 80,
    Std: 8
  },
  {
    student: "john",
    English: 80,
    Std: 8
  },
  {
    student: "john",
    Maths: 80,
    Std: 8
  }
];

and I need to get the total marks irrespective of subject for student sam.

By filtering data array by student name and then looping the filtered data, can get the individual student total marks.

Is there any groupBy function as similar to SQL in Typescript.

Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
anand
  • 1,559
  • 5
  • 21
  • 45

2 Answers2

1

This seems like it can be done with a simple reduce method on the array. Reduce will iterate over an array and pass each item into the provided predicate function. Each iteration should return the accumulator obj/array/val.

I wasn't sure what you wanted the data structure to be, but you can control the structure by the inner working of the function you pass to reduce.

  studentScores = this.data.reduce((accumulator, item) => {
    const key = Object.keys(item)
      .filter(k => k !== 'student')
      .filter(k => k !== 'Std')[0];
    const prevValue = accumulator[item.student] || 0;
    const studentName = item.student;
    accumulator[studentName] = prevValue + item[key];
    return accumulator;
  }, {});

I posted a working example in a stackblitz at https://stackblitz.com/edit/angular-xcjzzf

joshvito
  • 1,498
  • 18
  • 23
-2

You have to do it using dictionary. Easy way to grouping is used a map.there mark's name is changing so the task is difficult.This is stackblitz link.

Asanka
  • 1,628
  • 1
  • 10
  • 20