13

I've an array of objects with the following format

[{'list': 'one', 'item': 1},
 {'list': 'one', 'item': 2},
 {'list': 'one', 'item': 3},
 {'list': 'two', 'item': 1},
 {'list': 'two', 'item': 2}]

And I want to transform it like this

[{'one': [1, 2, 3]},
 {'two': [1, 2]}]

How can I do it using the Array.map function? Is it the best alternative?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ezequiel Miranda
  • 345
  • 4
  • 13

3 Answers3

18

You may use Array.prototype.reduce for your task. It allows a return value in the callback function for the next call.

var data = [
        { 'list': 'one', 'item': 1 },
        { 'list': 'one', 'item': 2 },
        { 'list': 'one', 'item': 3 },
        { 'list': 'two', 'item': 1 },
        { 'list': 'two', 'item': 2 }
    ],
    flat = data.reduce(function (r, a) {
        r[a.list] = r[a.list] || [];
        r[a.list].push(a.item);
        return r;
    }, {});

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

You're looking for a group-by method. This question has a nice answer: https://codereview.stackexchange.com/questions/37028/grouping-elements-in-array-by-multiple-properties

The code:

function groupBy(array, f)
{
  var groups = {};
  array.forEach(function(o)
  {
    var group = JSON.stringify(f(o));
    groups[group] = groups[group] || [];
    groups[group].push(o);
  });
  return Object.keys(groups).map(function(group)
  {
    return groups[group];
  })
}

var result = groupBy(list, function(item)
{
  return [item.lastname, item.age];
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Connor Clark
  • 671
  • 7
  • 15
2

To your specific question:

// Let x hold your array of objects.

res={}; // Create an empty object that will hold the answer

x.forEach (function (e) { // Use this function to iterate over each item in the list
    res[e.list] = res[e.list] || [];   // inspired by the Nina Scholz answer below
    res[e.list].push(e.item);   // Append the result to the array
 });
Ram Rajamony
  • 1,717
  • 15
  • 17
  • 2
    You should accept the Nina Scholz answer below. It is elegant, doesn't mutate a result variable, and offers up `reduce`, which is well worth learning about. It'll come in handy when/if you pick up functional programming. – Ram Rajamony Sep 16 '15 at 15:17