Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is a solution using ECMA5 methods</p> <p>Javascript</p> <pre><code>var makeRows1 = (function () { "use strict"; function reduceParticipants(previous, participant) { previous[participant.id] = [participant.name]; return previous; } function reduceResult(previous, subResult) { previous[subResult.participantId].push(subResult.answer); return previous; } function filterParticipants(participant) { return participant; } return function (participants, results) { var row = participants.reduce(reduceParticipants, []); results.forEach(function (result) { result.reduce(reduceResult, row); }); return row.filter(filterParticipants); }; }()); </code></pre> <p>This will not be as fast as using raw <code>for</code> loops, like @Esailija answer, but it's not as slow as you may think. It's certainly faster than using <code>Underscore</code>, like your example or the answer given by @Maroshii</p> <p>Anyway, here is a <a href="http://jsfiddle.net/fMBAe/" rel="nofollow">jsFiddle</a> of all three answers that demonstrates that they all give the same result. It uses quite a large data set, I don't know it compares to the size you are using. The data is generated with the following:</p> <p>Javascript</p> <pre><code>function makeName() { var text = "", possible = "abcdefghijklmnopqrstuvwxy", i; for (i = 0; i &lt; 5; i += 1) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; } var count, count2, index, index2, participants = [], results = []; for (index = 0, count = 1000; index &lt; count; index += 4) { participants.push({ id: index, name: makeName() }); } for (index = 0, count = 1000; index &lt; count; index += 1) { results[index] = []; for (index2 = 0, count2 = participants.length; index2 &lt; count2; index2 += 1) { results[index].push({ question: index, participantId: participants[index2].id, answer: "test" + index }); } } </code></pre> <p>Finally, we have a <a href="http://jsperf.com/make-rows-comparison" rel="nofollow">jsperf</a> that compares these three methods, run on the generated data set.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload