-1

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

SixtyEight
  • 2,220
  • 3
  • 14
  • 25
  • It's _undefined_, not null. Why not introduce a _condition_ to handle that case? – jonrsharpe May 29 '22 at 07:49
  • Please try: `console.log(countries.reduce((acc, { name, region }) => ((acc[region] ??= []).push({ name }), acc), {}));` and share your feedback. – jsN00b May 29 '22 at 07:49

2 Answers2

0

Suddenly I found the solution to my problem

const result = countries.reduce((acc, {
  name,
  region
}) => {
  return {
    ...(acc || {}),
    [region]: [...(acc[region] || []), {
      name
    }]
  }
}, {})
SixtyEight
  • 2,220
  • 3
  • 14
  • 25
0

You can solve the problem by defining acc[region]

const result = countries.reduce((acc, {
  name,
  region
}) => {
  if (!acc[region]) acc[region] = [];

  acc[region] = [...acc[region], {
    name
  }]

  return acc
}, {})