I have an array of object that contains different key value pairs and I’m trying to reduce this array of object using an another array.
I can refer the array that need to be reduced as the “Reducible Array” and the array I’m using to reduce as “Key array”.
Reducible Array:
JavaScript
x
24
24
1
[
2
{
3
"movie": {
4
"title": "Avengers",
5
"universe": "MARVEL",
6
"owned": "Walt Disney"
7
}
8
},
9
{
10
"movie": {
11
"title": "Captain America",
12
"universe": "MARVEL",
13
"owned": "Walt Disney"
14
}
15
},
16
{
17
"movie": {
18
"title": "Justice League",
19
"universe": "DC",
20
"owned": "Warner Bros"
21
}
22
}
23
]
24
Key Array:
JavaScript
1
2
1
[DC, MARVEL]
2
The reduced array of object I’m expecting after the operation is as follows.
Expected Result:
JavaScript
1
11
11
1
[
2
{
3
"Universe": "MARVEL",
4
"OwnedBy": "Walt Disney"
5
},
6
{
7
"Universe": "DC",
8
"OwnedBy": "Warner Bros"
9
}
10
]
11
What are all the operations I need to perform to get the expected result?
Advertisement
Answer
Since you naturally felt to use the word reduce
you must know that javascript offers such a method to reduce arrays:
JavaScript
1
38
38
1
const keyArray = ['DC', 'MARVEL'];
2
const array = [
3
{
4
"movie": {
5
"title": "Avengers",
6
"universe": "MARVEL",
7
"owned": "Walt Disney"
8
}
9
},
10
{
11
"movie": {
12
"title": "Captain America",
13
"universe": "MARVEL",
14
"owned": "Walt Disney"
15
}
16
},
17
{
18
"movie": {
19
"title": "Justice League",
20
"universe": "DC",
21
"owned": "Warner Bros"
22
}
23
}
24
];
25
26
const reducedObject = array.reduce((carry, {movie}) => {
27
const key = `${movie.universe}-${movie.owned}`;
28
29
if (keyArray.includes(movie.universe) && !carry.hasOwnProperty(key)) {
30
carry[key] = {universe: movie.universe, owned: movie.owned};
31
}
32
33
return carry;
34
}, {});
35
36
const reducedArray = Object.values(reducedObject);
37
38
console.log(reducedArray);