Array.sort with dynamically generated comparator
by hansenmc
HTML
<table>
<tr>
<td>
<div id="original" style="border: 1px solid green;width:300px"></div>
</td>
<td>
<div id="result" style="border:1px dashed red;width:300px"></div>
</td>
</tr>
</table>
<button>Name</button><button>Modified</button>
JavaScript
var list = [{
'Name': 'foo',
'Modified': '2012-01-01'
}, {
'Name': 'bar',
'Modified': '2010-01-01'
}, {
'Name': 'baz',
'Modified': '2012-10-01'
}, {
'Name': 'apple',
'Modified': '2012-01-11'
}, {
'Name': 'Banana',
'Modified': '2020-01-21'
}];
//============================================================
//A function that currys the prop value in the returned function
//=====================================================
function compareBy(prop){
var comparator = function(a, b) {
if (a[prop] < b[prop]) {
return -1;
}
if (a[prop] > b[prop]) {
return 1;
}
return 0;
};
return comparator;
};
$('#original').html(stringify(list));
$('#result').html(stringify(list.sort(compareBy('prop Doesnt exist'))));
$('button').click(function(){
var sortedList = list.sort(compareBy($(this).text()));
$('#result').html(stringify(sortedList));
});
function stringify(obj) {
if ("JSON" in window) {
return JSON.stringify(obj);
}
var t = typeof (obj);
if (t != "object" || obj === null) {
// simple data type
if (t == "string") obj = '"' + obj + '"';
return String(obj);
} else {
// recurse array or object
var n, v, json = [], arr = (obj && obj.constructor == Array);
for (n in obj) {
v = obj[n];
t = typeof(v);
if (obj.hasOwnProperty(n)) {
if (t == "string") {
v = '"' + v + '"';
} else if (t == "object" && v !== null){
v = jQuery.stringify(v);
}
json.push((arr ? "" : '"' + n + '":') + String(v));
}
}
return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
};