JSFiddle - React, Tailwind, and code Playground
by jfriend00
CSS
body {font-family: "Courier New"; font-size: 12px;}
JavaScript
var a = [];
a[0] = 31;
a[1] = 12;
a[2] = 666;
a[7] = 4;
a[8] = 053;
// sortFn is optional array sort callback function,
// defaults to numeric sort if not passed
function sortSparseArray(arr, sortFn) {
var tempArr = [], indexes = [];
for (var i = 0; i < arr.length; i++) {
// find all array elements that are not undefined
if (arr[i] !== undefined) {
tempArr.push(arr[i]); // save value
indexes.push(i); // save index
}
}
// sort values (numeric sort by default)
if (!sortFn) {
sortFn = function(a,b) {
return(a - b);
}
}
tempArr.sort(sortFn);
// put sorted values back into the indexes in the original array that were used
for (var i = 0; i < indexes.length; i++) {
arr[indexes[i]] = tempArr[i];
}
return(arr);
}
var output = JSON.stringify(sortSparseArray(a)).replace(/null/g, "undefined");
document.body.innerHTML = output;
a = [];
a[0] = "hello";
a[1] = "GoodBye";
a[2] = "whatever";
a[7] = "Fun";
a[8] = "Waterslide";
output = JSON.stringify(sortSparseArray(a, function(a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase())
})).replace(/null/g, "undefined");
document.body.innerHTML += "<br>" + output;