I have following array which consist of json objects:
JavaScript
x
39
39
1
items = [
2
{
3
id: '1',
4
name: 'Josh',
5
transactionDate: '2012-08-10',
6
creditAmount: '200',
7
numberBank: '12345',
8
},
9
{
10
id: '1',
11
name: 'Josh',
12
transactionDate: '2012-08-14',
13
creditAmount: '159',
14
numberBank: '12345',
15
},
16
{
17
id: '1',
18
name: 'Josh',
19
transactionDate: '2012-08-15',
20
creditAmount: '3421',
21
numberBank: '12345',
22
},
23
{
24
id: '2',
25
name: 'George',
26
transactionDate: '2012-09-15',
27
creditAmount: '6000',
28
numberBank: '13345',
29
},
30
{
31
id: '2',
32
name: 'George',
33
transactionDate: '2012-09-16',
34
creditAmount: '6565',
35
numberBank: '13345',
36
}
37
]
38
39
I want to separate the array index for each same id
as an example :
JavaScript
1
40
40
1
[
2
{
3
id: '1',
4
name: 'Josh',
5
transactionDate: '2012-08-10',
6
creditAmount: '200',
7
numberBank: '12345',
8
},
9
{
10
id: '1',
11
name: 'Josh',
12
transactionDate: '2012-08-14',
13
creditAmount: '159',
14
numberBank: '12345',
15
},
16
{
17
id: '1',
18
name: 'Josh',
19
transactionDate: '2012-08-15',
20
creditAmount: '3421',
21
numberBank: '12345',
22
}
23
],
24
[
25
{
26
id: '2',
27
name: 'George',
28
transactionDate: '2012-09-15',
29
creditAmount: '6000',
30
numberBank: '13345',
31
},
32
{
33
id: '2',
34
name: 'George',
35
transactionDate: '2012-09-16',
36
creditAmount: '6565',
37
numberBank: '13345',
38
}
39
]
40
How to do like that ? thanks
Advertisement
Answer
you can use reduce
to group by id
and then the values of the resultant using Object.values
EDIT
??=
is the Logical nullish assignment. The right hand side will be assigned whenever the left hand side is null
or undefined
.
JavaScript
1
9
1
let items = [ { id: '1', name: 'Josh', transactionDate: '2012-08-10', creditAmount: '200', numberBank: '12345', }, { id: '1', name: 'Josh', transactionDate: '2012-08-14', creditAmount: '159', numberBank: '12345', }, { id: '1', name: 'Josh', transactionDate: '2012-08-15', creditAmount: '3421', numberBank: '12345', }, { id: '2', name: 'George', transactionDate: '2012-09-15', creditAmount: '6000', numberBank: '13345', }, { id: '2', name: 'George', transactionDate: '2012-09-16', creditAmount: '6565', numberBank: '13345', } ]
2
3
const res = Object.values(items.reduce((acc,curr)=> {
4
acc[curr.id]??=[] //similar to acc[curr.id] = acc[curr.id] || [] in this case
5
acc[curr.id].push(curr)
6
return acc
7
},{}))
8
9
console.log(res)