I have the following array of object that I want to chance its structure , I am trying to use reduce to get a new object with element that have the same group..
JavaScript
x
16
16
1
const arr = [{id: 'c8c443', group: 'a', equipment: 'ball'},
2
{id: 'c84445', group: 'a', equipment: 'ball'},
3
{id: 'c8c655', group: 'b', equipment: 'basketball'},
4
{id: 'c8c634', group: 'b', equipment: 'basketball'}]
5
6
const newArr = arr.reduce(
7
(obj: any, value: any, i) => [
8
obj,
9
{
10
group: value.map((el: any) => el.group),
11
items: value.map((el: any) => el.equipment),
12
},
13
],
14
[]
15
);
16
// Results [{group: 'a', items: ['ball','ball']}, {group: 'b', items: ['basketball','basketball']}]
Advertisement
Answer
Here is an example:
JavaScript
1
19
19
1
const arr = [{id: 'c8c443', group: 'a', equipment: 'ball'},
2
{id: 'c84445', group: 'a', equipment: 'ball'},
3
{id: 'c8c655', group: 'b', equipment: 'basketball'},
4
{id: 'c8c634', group: 'b', equipment: 'basketball'}]
5
6
const newArr = arr.reduce((acc, item) => {
7
if (acc.some(key => key.group === item.group)) {
8
acc = acc.map(i => i.group === item.group ? {i, items: [i.items, item.equipment]} : i)
9
} else {
10
acc.push({
11
group: item.group,
12
items: [item.equipment]
13
})
14
}
15
16
return acc
17
}, [])
18
19
console.log(newArr)