Skip to content

Instantly share code, notes, and snippets.

@ubershmekel
Last active February 1, 2023 01:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ubershmekel/9ae7d845404cf8343e91ea0cd20f92fb to your computer and use it in GitHub Desktop.
Save ubershmekel/9ae7d845404cf8343e91ea0cd20f92fb to your computer and use it in GitHub Desktop.
Paste the following into a bookmark. When you're on a youtube channel's video page, you can now sort that page by view count. This new version works with the 2022 UI refresh that added rows to the mix.
javascript: function findMetrics(el) {
return el.textContent;
}
function findNodes(el) {
return el.querySelectorAll('#metadata-line');
}
function isDigit(str) {
return str.length === 1 && str.match(/[0-9]/i);
}
function metricVal(el) {
let modifiers = {
K: 1e3,
M: 1e6,
B: 1e9,
};
let text = findNodes(el)[0]?.textContent.trim();
if (!text) {
console.log('empty text');
return NaN;
};
const match = text.match(/\d+(\.\d+)?[KMB]?/);
if (!match) {
console.log("bad parse " + text);
return NaN;
}
const numText = match[0];
let number;
if (isDigit(numText[numText.length - 1])) {
number = +numText;
} else {
number = +numText.slice(0, -1);
const modChar = match[0].slice(-1);
number = number * modifiers[modChar];
}
console.log(`text: ${text}, numText: ${numText}, number: ${number}`);
return number;
}
function compare(el1, el2) {
let val1 = metricVal(el1);
let val2 = metricVal(el2);
if (val1 < val2) return 1;
if (val1 > val2) return -1;
return 0;
}
function findCommonParent(el1, el2) {
const seen = new Set();
let next = el1;
while (next) {
seen.add(next);
next = next.parentNode;
}
next = el2;
while (next) {
if (seen.has(next)) {
return next;
} else {
next = next.parentNode;
}
}
return null;
}
function main() {
let rows = [...document.querySelectorAll('#contents.ytd-rich-grid-row')];
let items = [];
for (const row of rows) {
for (const item of row.children) {
items.push(item);
}
}
const itemsPerRow = rows[0].children.length;
items.sort(compare);
for (let i = 0; i < items.length; i++) {
const row = rows[Math.floor(i / itemsPerRow)];
if (i % itemsPerRow === 0) {
row.innerHTML = '';
}
row.appendChild(items[i]);
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment