I have various styles of font objects grouped into arrays. Each font object has a property sub_family which is either Regular, Italic, Bold, Bold Italic (or some variation e.g. Italic is sometimes called Oblique). When they come out of the database they are in a random order and need to be sorted as above; Regular is always first, Italic second, etc.
Here’s the sort function I’m using, it works but I wanted to see if you guys could come up with better/alternate solutions:
// input: ["Bold Italic", "Regular", "Bold", "Italic"]
sortFont = function(a, b) {
// regular
if (/^([Rr]egular|[Nn]ormal)$/.test(a.sub_family)) { return -1; }
if (/^([Rr]egular|[Nn]ormal)$/.test(b.sub_family)) { return 1; }
// italic
if (/^([Ii]talic|[Ii]nclined|[Ii]t|[Oo]blique|[Oo]bl)$/.test(a.sub_family)) { return -1; }
if (/^([Ii]talic|[Ii]nclined|[Ii]t|[Oo]blique|[Oo]bl)$/.test(b.sub_family)) { return 1; }
// bold
if (/^([Bb]old|[Bb]d)$/.test(a.sub_family)) { return -1; }
if (/^([Bb]old|[Bb]d)$/.test(b.sub_family)) { return 1; }
}
// output: ["Regular", "Italic", "Bold", "Bold Italic"]
thanks! 🙂
Here’s a massively more efficient way of doing it that also lets you maintain it just by adding entries to a table:
Demo here: http://jsfiddle.net/jfriend00/MB76R/