Created
July 20, 2021 13:30
-
-
Save bekwam/1c543a7fff581dad3faf7032ca6bf528 to your computer and use it in GitHub Desktop.
JS Reduce Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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