I need to combine the gid and subGroups and output it into an array of strings without duplication.
My problem now is that it only gets the first level.
const oldGroup = [
{
"gid": "JFK",
"subGroups": [
"SFO",
"LAX"
]
},
{
"gid": "JFK",
"subGroups": [
"SFO",
"LAX"
]
},
{
"gid": "SFO",
"subGroups": []
},
{
"gid": "LAX",
"subGroups": [
"LGA"
]
}
]
const newGroup = [...new Set(oldGroup.map((group) => group.gid))]
console.log(newGroup)
There are several ways to achieve this, here is one with .reduce():
const oldGroup = [
{ "gid": "JFK", "subGroups": [ "SFO", "LAX" ] },
{ "gid": "JFK", "subGroups": [ "SFO", "LAX" ] },
{ "gid": "SFO", "subGroups": [] },
{ "gid": "LAX", "subGroups": [ "LGA" ] }
];
const newGroup = Object.keys(oldGroup.reduce((acc, obj) => {
acc[obj.gid] = true;
obj.subGroups.forEach(name => { acc[name] = true; } );
return acc;
}, {}));
console.log(newGroup)
Explanation:
.reduce() has two parameters:
acc, obj. The former is the accumulator that keeps track of the data needed, the latter is the array item object{} object in our caseObject.keys() is applied on the accumulated dataWith .flatMap instead of .map, return an array in the callback - the .gid value, and also spread in the .subGroups array.
const oldGroup = [
{
"gid": "JFK",
"subGroups": [
"SFO",
"LAX"
]
},
{
"gid": "JFK",
"subGroups": [
"SFO",
"LAX"
]
},
{
"gid": "SFO",
"subGroups": []
},
{
"gid": "LAX",
"subGroups": [
"LGA"
]
}
]
const newGroup = [...new Set(oldGroup.flatMap((group) => [group.gid, ...group.subGroups]))]
console.log(newGroup)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With