Skip to content

Instantly share code, notes, and snippets.

@bekwam
Created July 20, 2021 13:30
Show Gist options
  • Save bekwam/1c543a7fff581dad3faf7032ca6bf528 to your computer and use it in GitHub Desktop.
Save bekwam/1c543a7fff581dad3faf7032ca6bf528 to your computer and use it in GitHub Desktop.
JS Reduce Example
const starting = [
{
potentialUpgrades: ["D-a","D-b","D-c"],
productName: "D",
registeredUser: "test4.example.com"
},
{
potentialUpgrades: ["E-a","E-b","E-c"],
productName: "E",
registeredUser: "test4.example.com"
},
{
potentialUpgrades: ["101-1","101-2","101-3"],
productName: "101",
registeredUser: "test5.example.com"
}
];
console.log("starting=" + JSON.stringify(starting));
const ending = starting.reduce((acc, obj) => {
const item = acc.find( itm => itm.registeredUser == obj.registeredUser );
if( !item ){
acc.push({
registeredUser: obj.registeredUser,
products: [
{
productName: obj.productName,
potentialUpgrades: obj.potentialUpgrades
}]
});
} else {
item.products.push( {
productName: obj.productName,
potentialUpgrades: obj.potentialUpgrades
})
}
return acc;
}, [])
console.log("ending=" + JSON.stringify(ending));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment