I have an array
const countries = [{
name: "Angola",
region: "Africa"
}, {
name: "Spain",
region: "Europe"
}, {
name: "Italy",
region: "Europe"
}]
I need the result to be:
const result = {
Europe: [{
name: "Spain"
}, {
name: "italy"
}],
Africa: [{
name: "Angola"
}]
}
I've tried 2 approaches:
- Approach 1:
const result = countries.reduce((acc, {
name,
region
}) => {
acc[region] = [...acc[region], {
name
}]
return acc
}, {})
- Approach 2:
const result = countries.reduce((acc, {
name,
region
}) => {
return {
...acc,
[region]: [...acc[region], {
name
}]
}
}, {})
None of them work because I couldn't find a way to spread the existing items in the array, which at a first iteration is obviously null.
Thanks