var users = [{
name: "Вася",
surname: 'Иванов',
age: 20
}, {
name: "Петя",
surname: 'Чапаев',
age: 25
}, {
name: "Маша",
surname: 'Медведева',
age: 18
}];
function compare(a, b) {
return function (field){
return a[field] > b[field] ? 1 : -1;
}
}
var byField = compare();
users.sort(byField('name'));
users.forEach(function(user) {
alert( user.age );
});
function createCompare(field) {
return function (a, b){
if(a[field] > b[field]) return 1;
if(a[field] < b[field]) return -1;
return 0;
}
}
users.sort(createCompare('name'));
function compare(field) {
return function (a, b){
return a[field] > b[field] ? 1 : -1;
}
}
var byName = compare('name');
users.sort(byName);
users.forEach(function(user) {
alert( user.age );
});