MattDionis
MattDionis

Reputation: 3616

Remove duplicate objects, but push property to array on remaining object

I have an array of objects like so:

[
  {
    "id": "1",
    "location": "US"
  },
  {
    "id": "7",
    "location": "US"
  },
  {
    "id": "1",
    "location": "France"
  },
  {
    "id": "1",
    "location": "China"
  }
]

I would like to end up with a resulting array that looks like this:

[
  {
    "id": "1",
    "locations": ["US", "France", "China"]
  },
  {
    "id": "7",
    "locations": ["US"]
  }
]

Is there a solid way to accomplish this using underscore?

I'm contemplating looping through the array and for each id looping through the rest of the array and pushing location values to a locations array on that first object (by id), then at the end removing all duplicate objects (by id) which do not contain a locations property.

This is different from existing questions on SO that simply ask about removing duplicates. I am aiming to remove duplicates while also holding on to certain property values from these duplicates in an array on the 'surviving' object.

Upvotes: 2

Views: 870

Answers (3)

Gruff Bunny
Gruff Bunny

Reputation: 27986

And a version using underscore:

var result = _.chain(data)
    .groupBy('id')
    .map(function(group, id){
        return {
            id: id,
            locations: _.pluck(group, 'location')
        }
    })
    .value();

Upvotes: 1

madox2
madox2

Reputation: 51901

You can use reduce function to transform your array.

var data = [
    { "id": "1", "location": "US" },
    { "id": "7", "location": "US" },
    { "id": "1", "location": "France" },
    { "id": "1", "location": "China" }
];

var result = data.reduce(function (prev, item) {
    var newItem = prev.find(function(i) {
        return i.id === item.id;
    });
    if (!newItem) {
        prev.push({id: item.id, locations: [item.location]});
    } else {
        newItem.locations.push(item.location);
    }
    return prev;
}, []);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386746

Solution in plain Javascript

var data = [{ "id": "9" }, { "id": "1", "location": "US" }, { "id": "7", "location": "US" }, { "id": "1", "location": "France" }, { "id": "1", "location": "China" }],
    result = [];

data.forEach(function (a) {
    a.location && !result.some(function (b) {
        if (a.id === b.id) {
            b.locations.push(a.location);
            return true;
        }
    }) && result.push({ id: a.id, locations: [a.location] });
});

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Upvotes: 3

Related Questions