I want to keep the highest bitrate for each type of quality, so 1080p will keep the one with itag 137, and 720p will keep the itag with 398.
Here is my list with object arrays
JavaScript
x
30
30
1
[{
2
itag: 137,
3
container: 'mp4',
4
size: '33MB',
5
quality: '1080p',
6
bitrate: 1807211
7
},
8
{
9
itag: 399,
10
container: 'mp4',
11
size: '26MB',
12
quality: '1080p',
13
bitrate: 1335026
14
},
15
{
16
itag: 398,
17
container: 'mp4',
18
size: '13MB',
19
quality: '720p',
20
bitrate: 724723
21
},
22
{
23
itag: 136,
24
container: 'mp4',
25
size: '7MB',
26
quality: '720p',
27
bitrate: 414786
28
},
29
]
30
Advertisement
Answer
You can use the Array.prototype.reduce()
Method to reduce an array by iterating all items and returning the outgoing result.
In this case, we want to keep an Item of each quality. Therefore we reduce the Array by pushing items their qualities arent yet into the resulting array.
For further clarification and in depth details I always recommend to view the documentation of MDN Web Docs:
MDN Docs – Array.prototype.reduce()
JavaScript
1
39
39
1
const data = [{
2
itag: 137,
3
container: 'mp4',
4
size: '33MB',
5
quality: '1080p',
6
bitrate: 1807211
7
},
8
{
9
itag: 399,
10
container: 'mp4',
11
size: '26MB',
12
quality: '1080p',
13
bitrate: 1335026
14
},
15
{
16
itag: 398,
17
container: 'mp4',
18
size: '13MB',
19
quality: '720p',
20
bitrate: 724723
21
},
22
{
23
itag: 136,
24
container: 'mp4',
25
size: '7MB',
26
quality: '720p',
27
bitrate: 414786
28
},
29
];
30
31
// We iterate through all items of Data and reduce the Data to a new array
32
let res = data.reduce((a,b) => {
33
// We check if in the new Array already is an item with the same quality
34
// as the checking item, if not we insert it into the new array.
35
if(!a.find(item => item.quality === b.quality))
36
a.push(b);
37
return a;
38
}, []);
39
console.log(res);