/***** TWO IMPLEMENTATIONS *****/
function representFeaturedLabelsQuick (labels) {
// Remember smallest and second-smallest indices
var firstIndex = -1, secondIndex = -1;
var html = "";
for (var i = 0; i < labels.length; i++) {
// Is this label smaller than the current second-smallest?
if (secondIndex == -1 || labels[i] < labels[secondIndex]) {
// Is this label also smaller than the current smallest?
if (firstIndex == -1 || labels[i] < labels[firstIndex]) {
// This label is the smallest, so (re-)represent
html = "<div><span>" + labels[i] + "</span> <span>" +
labels[secondIndex] + "</span></div>";
firstIndex = i;
}
else {
// Replace the current second-smallest label
html = html.replace(labels[secondIndex], labels[i]);
secondIndex = i;
}
}
}
return html;
}
function representFeaturedLabelsElegant (labels) {
// Find the alphabetically first two labels
var featured = labels.sort().slice(0, 2);
// Return a <div> containing the first labels
return "<div><span>" + featured.join("</span> <span>") +
"</span></div>";
}
/***** TEST CASES *****/
test(["Anna", "Carl", "Bert"]);
test(["Bert", "Carl", "Anna"]);
test(["Carl"]);
/***** TEST UTILS *****/
function test (elements) {
show("Represent first two of", elements.join(", "));
show(" - quick: ", representFeaturedLabelsQuick(elements));
show(" - elegant:", representFeaturedLabelsElegant(elements));
show();
}
function show() {
var results = document.getElementById("results");
results.innerText += Array.prototype.join.call(arguments, " ") + "\n";
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.