function orderDescending(valueOne, valueTwo){
if(valueTwo > valueOne){
return 1;
}
if (valueTwo < valueOne) {
return -1;
}
else{return 0;}
}
function orderAscending(valueOne, valueTwo){
if(valueTwo > valueOne){
return -1;
}
if (valueTwo < valueOne) {
return 1;
}
else{return 0;}
}
var numbers = [1,4,27,4,8,0];
numbers.sort(orderAscending);
//alert(numbers);
numbers.sort(orderDescending);
//alert(numbers);
But We can improve it, in this way ...
function Comparator(propertyName) {
return function(objectOne, objectTwo){
var valueOne = objectOne[propertyName];
var valueTwo = objectTwo[propertyName];
if (value1 < value2){
return -1;
} else if (value1 > value2){
return 1;
} else {
return 0;
}
};
}
And We can use it in this way
var data = [{name: “PersonOne”, age: 1}, {name: “PersonTwo”, age: 2}];
data.sort(Comparator(“name”));
No hay comentarios:
Publicar un comentario