I have an array of objects, these objects have a property that I want to group by. So my goal is to produce a new array of objects where they have all the same properties with an additional property that consolidates all the “value” properties into an array.
Below is my input and desired output. How could I accomplish this ?
INPUT
[ { group_by_this_property: 1, value: 100, class: 'A', }, { group_by_this_property: 1, value: 101, class: 'A', }, { group_by_this_property: 1, value: 102, class: 'A', }, { group_by_this_property: 2, value: 200, class: 'B', }, { group_by_this_property: 2, value: 201, class: 'B', } ]
OUTPUT
[ { group_by_this_property: 1, values: [100, 101, 102], class: 'A', }, { group_by_this_property: 2, values: [200, 201], class: 'B', }, ]
Advertisement
Answer
You can group the items using a Map and return the values in the end as follows:
const data = [ { group_by_this_property: 1, value: 100, class: 'A' }, { group_by_this_property: 1, value: 101, class: 'A' }, { group_by_this_property: 1, value: 102, class: 'A' }, { group_by_this_property: 2, value: 200, class: 'B' }, { group_by_this_property: 2, value: 201, class: 'B' } ]; const res = [... data.reduce((map, { group_by_this_property, value, ...props }) => { const { values = [] } = map.get(group_by_this_property) ?? {}; values.push(value); map.set(group_by_this_property, { ...props, group_by_this_property, values}); return map; }, new Map) .values() ]; console.log(res);