We have an array of objects with the attributes "description" and "id".
foo[0].id // "45g-332"
foo[0].id2 // "45G-000332"
foo[0].description // "tomatoes"
foo[1].id // "45f-842"
foo[1].id2 // "45F-000842"
foo[1].description // "cherries"
foo[2].id // "45g-332"
foo[2].id2 // "45G-000332"
foo[2].description // "peaches"
I need a variable or object in which all descriptions for the same id are combined to have a result like this:
bar[0].id // "45g-332"
bar[0].id2 // "45G-000332"
bar[0].description // "tomatoes; peaches"
bar[1].id // "45f-842"
bar[1].id2 // "45F-000842"
bar[1].description // "cherries"
… or with associative labels
bar["45g-332"].description // "tomatoes; peaches"
bar["45f-842"].description // "cherries"
bar["45g-332"].id2 // "45G-000332"
The only passably slim solution I came up with is (→ jsFiddle):
let foo = [];
foo[0] = [];
foo[1] = [];
foo[2] = [];
foo[0].id = "45g-332";
foo[0].id2 = "45G-000332";
foo[0].description = "tomatoes";
foo[1].id = "45f-842";
foo[1].id2 = "45F-000842";
foo[1].description = "cherries";
foo[2].id = "45g-332";
foo[2].id2 = "45G-000332";
foo[2].description = "peaches";
let bar = [];
for (let i in foo) { // Loop through source (foo)
if (bar[foo[i].id]) { // Check if sink (bar) with id already exists
bar[foo[i].id].description += "; " + foo[i].description; // Add description to existing bar element
} else {
bar[foo[i].id] = []; // Create new bar element
bar[foo[i].id].description = foo[i].description;
};
bar[foo[i].id].id2 = foo[i].id2; // Added by edit
};
for (let i in bar) {
console.log("id: " + i + " has: " + bar[i].description + " and id2: " + bar[i].id2);
};
// Result is
// "id: 45g-332 has: tomatoes; peaches and id2: 45G-000332"
// "id: 45f-842 has: cherries and id2: 45F-000842"
I'm pretty sure that there's a more plain way to do this. What's gold standard?