function getOrdinal(n) {
var s=["th","st","nd","rd"],
v=n%100;
return n+(s[(v-20)%10]||s[v]||s[0]);
}
-
-
Save tomysmile/682b5a12214f6cae1f47 to your computer and use it in GitHub Desktop.
beautiful
i was annoyed javascript doesn't include this in the programming language
but it kinda exists as a programming challenge
having been humbled repeatedly by programming since the early 2000s...i sought a solution on google. there was an ai solution that used an api that is likely unavailable on legacy browsers...i guess another obstacle to implementing this into the js language is backwards compatibility.
tbh javascript is kinda obligated to release backwards compatibility libraries...especially with the new Temporal API I discovered browsing the the wikipedia article for Software...imagine using a website and all time related functionality is straight up broken lol.
your solution is very elegant and concise, i took some time to understand the logic, partially inspired by keshavgupta848101
(v-20)%10 is the key for skipping eleventh, twelfth (lol english is my first language and I FORGOT HOW TO SPELL THIS, kept trying to use v), thirteenth ordinals that might (il)logically use 11st 12nd 13rd.
TIL (reminder) return (false || true)
honestly you deserve an award for this solution (pending benchmarks). my only modifications would be perhaps
const s=["th","st","nd","rd"]; function toOrdinal(n) { let v=n%100; return n+(s[(v-20)%10]||s[v]||s[0]); }
edit: unsure why code block collapses newlines
also just realized it's unsanitary to define the ordinal suffixes outside of the function...
I was worried about it getting redefined after every call. idk if javascript compiler is intelligent enough to cache the variable.
the solution is probably to define it as a const in a number formatting class...really this ought to be part of the language.
having it in Intl.NumberFormat would be excellent as different locales -likely- 💯% have different ordinals
just goes to prove that JavaScript is an incomplete language (hey I'm an incomplete person, we're all constantly striving for improvement).
I am on a quest to output the date as follows: Sunday, December 28th, 2025
this has proved to be a gargantuan task filled with scope creep and has wasted over an hour of my time.
function makeItOrdinal(numbers) {
const newArray = [];
for (n of numbers) {
let s = ["th", "st", "nd", "rd"];
let temp = n % 100;
newArray.push(n + (s[(temp - 20) % 10] || s[temp] || s[0]));
}
return newArray;
}
const numbers = [1, 2, 3, 4, 5, 6, 7];
Please explain this