Skip to content

Instantly share code, notes, and snippets.

@jozsefs
Last active October 5, 2017 06:45
Show Gist options
  • Save jozsefs/19f2416b165e538d286ac985b6fc6219 to your computer and use it in GitHub Desktop.
Save jozsefs/19f2416b165e538d286ac985b6fc6219 to your computer and use it in GitHub Desktop.
Sort youtube videos by views - channel videos or searched videos
(() => {
const channelVideosGrid = document.querySelector('[page-subtype=channels] #items');
const grid = channelVideosGrid;
const MULTIPLIER = {
k: 1000,
m: 1000 * 1000,
b: 1000 * 1000 * 1000
};
if (!grid) {
throw new Error('It won\'t work on this page.');
}
const itemSelector = 'ytd-grid-video-renderer';
const viewSelector = '#metadata-line span:first-child';
const items = [].map.call(document.querySelectorAll(itemSelector), (item) => {
const matches = item.querySelector(viewSelector).innerText.match(/([0-9.]+)(K|M)?/i);
const views = matches[2] ? MULTIPLIER[matches[2].toLowerCase()] * parseInt(matches[1], 10) : parseInt(matches[1], 10);
return {
item,
views
};
});
if (!items.length) {
throw new Error('If the list is not empty the CSS selector needs to be updated');
}
items.sort((a,b) => {
if (a.views < b.views) return 1;
if (a.views > b.views) return -1;
return 0;
});
items.forEach((item, idx) => {
grid.appendChild(items[idx].item);
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment