JSFiddle - React, Tailwind, and code Playground
CSS
p span{
color:green;
}
p span.f{
color:red;
}
JavaScript
// That function separates objects with truthy or falsy properties
// and joins them back to keep their order
Array.prototype.booleanSortBy = function(property){
var res = {true : [], false: []};
for(var i=0, l=this.length; i<l; i++){
res[ this[i][property] ].push( this[i] );
}
return res[true].concat( res[false] );
}
var unsorted = randomArray(26);
printArray('Unsorted', unsorted);
var sorted = unsorted.booleanSortBy('x');
printArray('Sorted', sorted);
// Utility function to get a random array
// of Objects having a name and a random boolean (x).
// Names are letters in alphabetical order, to keep track of them
// Truthy values have an uppercase name, and vice versa
function randomArray(n){
var res = [],
index = {true:0, false:0};
while(n--){
var bool = !!Math.round(Math.random());
res.push({
name : String.fromCharCode((bool?65:97) + index[bool]),
x : bool
});
index[bool]++;
}
return res;
}
// Utility function to print the arrays on the page
function printArray(label, arr){
var res = '<p>';
for(var i=0,l=arr.length; i<l; i++){
res += '<span'+ (arr[i].x?'':' class="f"') +'>'+arr[i].name+'</span>';
}
document.body.insertAdjacentHTML('beforeend','<h2>'+label+'</h2>'+res+'</p>');
}