logo hsb.horse
← Back to blog index

Blog

TypeScript Implementation for Sorting Media Files by Resolution

A concise TypeScript implementation for sorting videos or images by resolution (width × height). Useful for ordering Twitter media variants.

Published:

This is code I wrote when I needed to sort something like Twitter video media by resolution.

Sort by Resolution (Width × Height) in Descending Order

interface MediaFile {
url: string;
height: number;
width: number
}
function sortMediaByQuality(files: Array<MediaFile>): Array<MediaFile> {
return files.toSorted((a, b) => {
const resolutionA = a.width * a.height;
const resolutionB = b.width * b.height;
return resolutionB - resolutionA
});
}

Key Points

  • toSorted: returns a new array without mutating the original one
  • Resolution calculation: compute resolution with width × height
  • Descending sort: place larger resolutions first

Example

const videos: MediaFile[] = [
{ url: "video1.mp4", width: 1280, height: 720 }, // 921,600
{ url: "video2.mp4", width: 1920, height: 1080 }, // 2,073,600
{ url: "video3.mp4", width: 640, height: 480 }, // 307,200
];
const sorted = sortMediaByQuality(videos);
// video2.mp4 (1920x1080) comes first

Summary

Combining resolution calculation with sorting makes it easy to prioritize higher-quality media files.

It works well when selecting the best candidate from multiple video or image variants, such as Twitter media.