user2000212
user2000212

Reputation:

Read json return values and average a field value with count using javascript

My return value from api call is as below

 var array = {"scores":[
      { userid: "1", mark: 4.3 },
      { userid: "1", mark: 3.8 },
      { userid: "2", mark: 4.6 },
      { userid: "2", mark: 4.1 },
      { userid: "2", mark: 3.9 },
      { userid: "2", mark: null}
    ]};

The expected output should match the userid with the average of mark and total count. we should not consider if the value of mark is null

var arr = [
  { userid: "1", mark: 4.05, count: 2 },
  { userid: "2", mark: 4.2, count: 3}
]

i have tried with the below script but it gives error - array.scores[0].reduce is not a function

 result = Array.from(
            array.scores[0].reduce((m, { userid, mark}) => {
                var temp = m.get(userid) || { sum: 0, count: 0 };
                temp.sum += mark;
                temp.count++;
                return m.set(userid, temp);
            }, new Map),
            ([externalCourse, { sum, count }]) => ({ userid, average: sum / count, count })
        );
console.log(result);

Upvotes: 0

Views: 45

Answers (1)

Derek Wang
Derek Wang

Reputation: 10204

Using Array.prototype.reduce, you can group the input by userid and based on that grouped object information, you can calculate the average of the marks as follows.

const input = {
  "scores": [{
      userid: "1",
      mark: 4.3
    },
    {
      userid: "1",
      mark: 3.8
    },
    {
      userid: "2",
      mark: 4.6
    },
    {
      userid: "2",
      mark: 4.1
    },
    {
      userid: "2",
      mark: 3.9
    }
  ]
};

const groupBy = input.scores.reduce((acc, cur) => {
  acc[cur.userid] ? acc[cur.userid].mark.push(cur.mark) : acc[cur.userid] = {
    userid: cur.userid,
    mark: [ cur.mark ]
  };
  return acc;
}, {});
const output = Object.values(groupBy).map((item) => ({
  userid: item.userid,
  count: item.mark.length,
  mark: item.mark.reduce((acc, cur) => acc + cur, 0) / item.mark.length
}));
console.log(output);

Upvotes: 1

Related Questions