JavaScript
x
43
43
1
const vehicle = [
2
{
3
a: [
4
{
5
vehicle_name: "Toyota",
6
color: "black"
7
},
8
{
9
vehicle_name: "Toyota",
10
color: "red"
11
},
12
{
13
vehicle_name: "Ford",
14
color: "yellow"
15
},
16
{
17
vehicle_name: "Toyota",
18
color: "white"
19
}
20
]
21
},
22
{
23
b: [
24
{
25
vehicle_name: "Honda",
26
color: "black"
27
},
28
{
29
vehicle_name: "Honda",
30
color: "red"
31
},
32
{
33
vehicle_name: "Ford",
34
color: "yellow"
35
},
36
{
37
vehicle_name: "Toyota",
38
color: "white"
39
}
40
]
41
}
42
]
43
Given the array of obj above, My goal is to get the total number of vehicle in each key. Note: if the vehicle_name is repeated it should only count as 1. Expected Output:
JavaScript
1
13
13
1
const result = [
2
{
3
a: {
4
count: 2
5
}
6
},
7
{
8
b: {
9
count: 3
10
}
11
}
12
]
13
Explanation: The count of key a => is 2 because although it have 4 vehicles but Toyota is repeated so it only count as 1. Same goes in key b => the count is 3 because it has three different name(Honda, Ford, Toyota)
Advertisement
Answer
You can use map
to iterate the objects in vehicle
, then Object.entries
to iterate those objects, using reduce
to count the unique vehicles seen in the objects in each array value:
JavaScript
1
34
34
1
const vehicle = [
2
{
3
a: [
4
{ vehicle_name: "Toyota", color: "black" },
5
{ vehicle_name: "Toyota", color: "red" },
6
{ vehicle_name: "Ford", color: "yellow" },
7
{ vehicle_name: "Toyota", color: "white" }
8
]
9
},
10
{
11
b: [
12
{ vehicle_name: "Honda", color: "black" },
13
{ vehicle_name: "Honda", color: "red" },
14
{ vehicle_name: "Ford", color: "yellow" },
15
{ vehicle_name: "Toyota", color: "white" }
16
]
17
}
18
]
19
20
const result =
21
vehicle.map(o => Object.fromEntries(
22
Object.entries(o).map(([k, a]) => [k, { count :
23
a.reduce((acc, { vehicle_name }) => {
24
if (!(vehicle_name in acc)) {
25
acc[vehicle_name] = 1
26
acc.count++
27
}
28
return acc
29
}, { count: 0 }).count }
30
])
31
)
32
)
33
34
console.log(result)