I'm trying to group objects that have the same property together. I'm starting with an array of objects, and I want to end up with an array that contains several arrays each with the objects that share the same property.
Say I have this array of film objects, they all have a year property, and I want to group all the films with the same year property in their own array and finally have all of those arrays in a single array.
// This is the array I've got
const films = [
{
name='film 1',
year='1992'
},
{
name='film 2',
year='1992'
},
{
name='film 3',
year='1995'
},
{
name='film 4',
year='1995'
},
{
name='film 5',
year='1995'
},
{
name='film 6',
year='1998'
},
{
name='film 7',
year='1998'
},
]
// And this is the array I want to end up with
const filmsSorted = [
[
{
name='film 1',
year='1992'
},
{
name='film 2',
year='1992'
},
]
[
{
name='film 3',
year='1995'
},
{
name='film 4',
year='1995'
},
{
name='film 5',
year='1995'
},
]
[
{
name='film 6',
year='1998'
},
{
name='film 7',
year='1998'
},
]
]
Bear in mind that I don't have the year property in advance and must deal dynamically with whatever year I receive in the original array.
While there are plenty of questions about sorting and filtering arrays on here, I couldn't find an answer to this specific problem. I tried to use reduce() and filter() and a combination of them, but I just can't seem to get my head around it. I have found some possible solutions (transforming it into an object and back into an array) but what I would really like is to see a few different ways that this might be solved to help me reason about it better.