'Convert array of objects into subarrays of objects by a selected property (javascript)

I am looking to take an array of objects, and convert it into an array of subarrays based on a chosen object property

for example:

[
  {foo: 1, bar: a}, {foo: 2, bar: b}, {foo: 1, bar: c}, {foo: 2, bar: d}
]

Create subarrays with the foo property would become:

[
  [
    {foo: 1, bar: a}, {foo: 1, bar: c}, 
  ],
  [
    {foo: 2, bar: b}, {foo: 2, bar: d}
  ]
]

I can't think of an efficient way to this. I keep resorting to creating a set of all of the unique property values of my chosen value, and then brute forcing through it multiple times.

const distinctProperties =  [...new Set(originalArray.map(item => item.foo))]

const newArray = distinctProperties.map(item => originalArray.filter(obj => obj.foo === item))

Thanks in advance for some advice here!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source