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
[{
itag: 137,
container: 'mp4',
size: '33MB',
quality: '1080p',
bitrate: 1807211
},
{
itag: 399,
container: 'mp4',
size: '26MB',
quality: '1080p',
bitrate: 1335026
},
{
itag: 398,
container: 'mp4',
size: '13MB',
quality: '720p',
bitrate: 724723
},
{
itag: 136,
container: 'mp4',
size: '7MB',
quality: '720p',
bitrate: 414786
},
]
CodePudding user response:
Here is the simple solution, https://stackblitz.com/edit/js-3gijty?file=index.js
const videos = [
{
itag: 137,
container: 'mp4',
size: '33MB',
quality: '1080p',
bitrate: 1807211,
},
{
itag: 399,
container: 'mp4',
size: '26MB',
quality: '1080p',
bitrate: 1335026,
},
{
itag: 398,
container: 'mp4',
size: '13MB',
quality: '720p',
bitrate: 724723,
},
{
itag: 136,
container: 'mp4',
size: '7MB',
quality: '720p',
bitrate: 414786,
},
];
const uniqueHighestBitrateVideos = [];
const presetQuality = [];
const sortByBitrate = videos.sort((a, b) => b.bitrate - a.bitrate);
sortByBitrate.forEach((eachItem) => {
if (!presetQuality.includes(eachItem.quality)) {
presetQuality.push(eachItem.quality);
uniqueHighestBitrateVideos.push(eachItem);
}
});
CodePudding user response:
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()
const data = [{
itag: 137,
container: 'mp4',
size: '33MB',
quality: '1080p',
bitrate: 1807211
},
{
itag: 399,
container: 'mp4',
size: '26MB',
quality: '1080p',
bitrate: 1335026
},
{
itag: 398,
container: 'mp4',
size: '13MB',
quality: '720p',
bitrate: 724723
},
{
itag: 136,
container: 'mp4',
size: '7MB',
quality: '720p',
bitrate: 414786
},
];
// We iterate through all items of Data and reduce the Data to a new array
let res = data.reduce((a,b) => {
// We check if in the new Array already is an item with the same quality
// as the checking item, if not we insert it into the new array.
if(!a.find(item => item.quality === b.quality))
a.push(b);
return a;
}, []);
console.log(res);