/* "Sort by, then by"
// Based on this jsfiddle:
// http://jsfiddle.net/dFNva/1/
// as a response to this stackoverflow post:
// http://stackoverflow.com/a/979325/2502532
// Improvements include JSON deep access with path notation, 'then by' sorting.
// Description: Sort by object key, with optional reverse ordering, priming, and 'then by' sorting.
array.sort(
by(path[, reverse[, primer[, then]]])
);
*/
/* THE FUNCTION */
var by = function (path, reverse, primer, then) {
var get = function (obj, path) {
if (path) {
path = path.split('.');
for (var i = 0, len = path.length - 1; i < len; i++) {
obj = obj[path[i]];
};
return obj[path[len]];
}
return obj;
},
prime = function (obj) {
return primer ? primer(get(obj, path)) : get(obj, path);
};
return function (a, b) {
var A = prime(a),
B = prime(b);
return (
(A < B) ? -1 :
(A > B) ? 1 :
(typeof then === 'function') ? then(a, b) : 0
) * [1,-1][+!!reverse];
};
};
/* THE ARRAY */
var arr = [
"1951-1207",
"1951-1324",
"1951-1325",
"1951-196",
"1951-28",
"1952-1068",
"1952-1204",
"1952-1224",
"1952-397",
"1952-69",
"1952-748"
];
/* THE EXAMPLES */
/* Sort generic */
arr.sort();
// Output
var t1 = document.getElementById('t1');
t1.innerHTML += '<caption>Sort generic</caption>';
for (var i = 0; i < arr.length; i++) {
t1.innerHTML += '<tr><td>' + arr[i] + '</td></tr>';
}
/* Sort by, then by */
arr.sort(
by(null, false,
function (x) {
var y = x.split('-');
return parseFloat(y[0]);
},
by(null, false,
function (x) {
var y = x.split('-');
return parseFloat(y[1]);
}
)
)
);
// Output
var t2 =...
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.
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!
Console
Debug your Fiddle with a minimal built-in JavaScript console.