JSFiddle - React, Tailwind, and code Playground
by Julien Etienne
HTML
<h2>Original</h2>
<div></div>
<h2>lexicographical Ascending</h2>
<div></div>
<h2>lexicographical Descending</h2>
<div></div>
<h2>Numeric Ascending</h2>
<div></div>
<h2>Numeric Descending</h2>
<div></div>
<h2>Test</h2>
<div></div>
<h2>Test2</h2>
<div></div>
<div></div>
<div></div>
<div></div>
CSS
div {
height:2em;
position:relative;
float:left;
width: 100%;
font-family: arial;
}
h2 {
font-size: 1rem;
line-height: 1rem;
margin:0.3rem 0 0 0;
}
JavaScript
var div = document.getElementsByTagName('div'),
nums = [5, 2, 6, 51, 2, 20, 3, , , , 1, 3, 45, 0.4, , 59, 87, 'a', 'c', 'd', 'b', 345, 400, 1000, 0.123],
animals = ['lions', 1000, 'tigers', 'monkeys', , , 50, 0.4, 'sharks', 'dolphins', 'mice', 'cats', 3, 97, 'rabbits'],
lexical = nums.slice(),
lexicalReverse = nums.slice(),
numeric = nums.slice(),
numericDesc = nums.slice(),
test = nums.slice(),
test2 = animals.slice(),
// lexicographicallly Ascending
lexical = lexical.sort(),
// lexicographically Descending
lexicalReverse = lexicalReverse.sort().reverse(),
// numeric Ascending
numeric = numeric.sort(testFunction);
function testFunction(a, b) {
return a - b;
//return a.localeCompare(b);
}
// numeric Descending
numericDesc = numericDesc.sort(testFunctionDesc);
function testFunctionDesc(a, b) {
return b - a;
}
// Get Numbers From Array
Array.prototype.getArrayNumbers = function () {
var _this = this;
for (var i = _this.length; i--;) {
if (typeof (_this[i]) !== 'number') _this.splice(i, 1);
}
return _this;
};
// Sort Numerically
Array.prototype.sortNumerically = function (direction) {
var _this = this;
function comparator(a, b) {
return direction < 0 ? b - a : a - b;
}
return _this.sort(comparator);
};
// Chain
test.getArrayNumbers().sortNumerically(-1);
// Sort Numerically
// Get strings From Array
Array.prototype.getArrayStrings = function () {
var _this = this;
for (var i = _this.length; i--;) {
if (typeof (_this[i]) !== 'string') _this.splice(i, 1);
}
return _this;
};
// Sort Alphabetically
Array.prototype.sortAlphabetically = function (direction) {
var _this = this;
function comparator(a, b) {
if (direction < 0) {
return a == b ? 0 : a < b ? -1 : 1;
} else {
return a == b ? 0 : a > b ? -1 : 1;
}
}
return _this.sort(comparator);
};
//...