1

I'm out of inspiration and probably is very simple what I have to do but idk.

Let's say we have this array :

var answers = [
  {
    name: 'Name 1',
    score: 5,
    correct_ans: 'y'
    challenge: ....
  },
  {
    name: 'Name 2',
    score: 10,
    correct_ans: 'n',
    challenge: ....
  },
  {
    name: 'Name 1',
    score: 12,
    correct_ans: 'y',
    challenge: ....
  },
  {
    name: 'Name 2',
    score: 8,
    correct_ans: 'y',
    challenge: ....
  }
]

So what I need from questions array is another array like this:

var array = [
 {
   name: 'Name1',
   overall_score: --total score-- if the correct_ans is y
   score: [
     {
      score: 5,
      challenge: ....
     }
   ]
 }
]

And so on .. Basically I want to create a leaderboard out of a table of answers. I managed to extract the objects without repeating them I'm not sure if this help me : https://plnkr.co/edit/rXRrPc1MrSs181GBv8tf?p=preview

Shaker
  • 33
  • 7
  • Possible duplicate of [What is the most efficient method to groupby on a javascript array of objects?](http://stackoverflow.com/questions/14446511/what-is-the-most-efficient-method-to-groupby-on-a-javascript-array-of-objects) – Manuel S. Mar 24 '16 at 09:08
  • 1
    Yeah but from what I see there are a lot of things that I don't understand. But thanks for the link it might help in the future. – Shaker Mar 24 '16 at 09:25

1 Answers1

2

You can iterate and build a new array with the grouped data.

var questions = [{ team_name: 'Team A', points: 0, correct_ans: 'n' }, { team_name: 'Team B', points: 10, correct_ans: 'y' }, { team_name: 'Team A', points: 15, correct_ans: 'y' }, { team_name: 'Team B', points: 15, correct_ans: 'y' }, { team_name: 'Team A', points: 20, correct_ans: 'y' }, { team_name: 'Team B', points: 20, correct_ans: 'y' }],
    array = function (array) {
        var r = [];
        array.forEach(function (a) {
            if (a.correct_ans !== 'y') {
                return;
            }
            if (!this[a.team_name]) {
                this[a.team_name] = { team_name: a.team_name, overall_score: 0, score: [] };
                r.push(this[a.team_name]);
            }
            this[a.team_name].overall_score += a.points;
            this[a.team_name].score.push({ points: a.points, correct_ans: a.correct_ans });
        }, {});
        return r;
    }(questions);

document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392