In this article, we are going to learn how we can sort YouTube channel videos by video duration.
We can sort video from low-to-high
and high-to-low
video duration. EG: 0:10 to 10:00
.
To sort YouTube videos, I have created a package and we are going use that package. Package name is sort-youtube-videos.
First of all, we have to install the package:
npm i sort-youtube-videos
OR if you prefer YARN
yarn add sort-youtube-videos
let's import this package
// if you want to use require
const { sortByDuration } = require("sort-youtube-videos");
//OR
// if you are want to use import
import { sortByDuration } fro"sort-youtube-videos";
// more code ...
To sort videos:
const url = "https://www.youtube.com/channel/UC5RRWuMJu7yP1DQwnW_nAvA"; //enter channel url or channel id
const sortBy = "sl"; // options: sl - ls
sortByDuration(url, sortBy).then((res) => console.log(res));
Note sl
means short to long
and ls
means long to short
And this is the response we will get back:
[
{
type: "video",
title: "Ramadan Ki Shan Episode 11 Digitally Presented by Spiced Foods",
videoId: "dgoBBYbSKUQ",
author: "Anas and Ammar",
authorId: "UC5RRWuMJu7yP1DQwnW_nAvA",
videoThumbnails: [[Object], [Object], [Object], [Object]],
viewCountText: "15 views",
viewCount: 15,
publishedText: "5 months ago",
durationText: "4:09",
lengthSeconds: 249,
liveNow: false,
premiere: false,
premium: false,
},
{
type: "video",
title:
"Watch latest movies, web series and TV channels for free without any subscription ||Android",
videoId: "ummVLFK17GI",
author: "Anas and Ammar",
authorId: "UC5RRWuMJu7yP1DQwnW_nAvA",
videoThumbnails: [[Object], [Object], [Object], [Object]],
viewCountText: "16 views",
viewCount: 16,
publishedText: "1 year ago",
durationText: "4:11",
lengthSeconds: 251,
liveNow: false,
premiere: false,
premium: false,
},
// ... 109 more items
];
Here's the full code:
const { sortByDuration } = require("sort-youtube-videos");
const url = "https://www.youtube.com/channel/UC5RRWuMJu7yP1DQwnW_nAvA"; //url or channel id
const sortBy = "sl"; // options: sl - ls
sortByDuration(url, sortBy).then((res) => console.log(res));
To sum up
This process of sorting YouTube videos can take some time and this process might not be that efficient. Because we are fetching all videos from a YouTube channel and than a sorting algorithm will sort the videos. But there might be 1000 video's or more videos on the channel.
So, you might ask...
What will be a better solution?
There is no other solution right now.
If YouTube officially provide this feature than it will be more efficient.
That pretty much it. I hope you found this article helpful.
Happy Coding:)
Top comments (0)