2

I have the following array of people:

const people = [
  { name: 'Tom Hiddleston', country: 'UK' },
  { name: 'Joe Biden', country: 'USA' },
  { name: 'James Bond', country: 'UK' },
  { name: 'Barack Obama', country: 'USA' },
  { name: 'Dolph Lundgren', country: 'SWEDEN' },
];

Now I want to break this array into multiple arrays based on the country property.

Basically I want a magic function that does the following:

const peopleGroupedByCountry = magicFunction(people);
console.log(peopleGroupedByCountry);

// Should log the following:
[
  [
    { name: 'Tom Hiddleston', country: 'UK' },
    { name: 'James Bond', country: 'UK' },
  ],
  [
    { name: 'Joe Biden', country: 'USA' },
    { name: 'Barack Obama', country: 'USA' },
  ],
  [
    { name: 'Dolph Lundgren', country: 'SWEDEN' },
  ]
]
3
  • stackoverflow.com/questions/14696326/… Commented Mar 24, 2021 at 7:54
  • 2
    @PranayNailwal Well that link leads to answers using underscore and jquery, not what I was after. Terry Lennox answer here is in pure vanilla js, and works perfectly. Commented Mar 24, 2021 at 7:59
  • 4
    I would recommend Terry's answer since it's much modern and elegant while the referenced Q&A is about 8 years Commented Mar 24, 2021 at 8:00

1 Answer 1

10

You can use Array.reduce to do this, we create an object with keys for each country.

We can then use Object.values to get this as an array.

const people = [
    { name: 'Tom Hiddleston', country: 'UK' },
    { name: 'Joe Biden', country: 'USA' },
    { name: 'James Bond', country: 'UK' },
    { name: 'Barack Obama', country: 'USA' },
    { name: 'Dolph Lundgren', country: 'SWEDEN' },
];

const grouped = Object.values(people.reduce((acc, item) => {
    // Append the item to the array for each country
    acc[item.country] = [...(acc[item.country] || []), item];
    return acc;
}, {}))

console.log(grouped)

Sign up to request clarification or add additional context in comments.

3 Comments

It would be better to add another parameter to assign which key should be the reference to group with
Works perfectly, and in vanilla js as well! Unlike whoever closed my question as already answered, referring to a 8 year old post with accepted answers using jQuery and underscore, which is not relevant to my question. Anyway, thanks!
Also enjoyed this answer vs the referred "already answered" post

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.