我使用AJAX获取了以下对象,并将它们存储在数组中:
var homes = [
{
"h_id": "3",
"city": "Dallas",
"state": "TX",
"zip": "75201",
"price": "162500"
}, {
"h_id": "4",
"city": "Bevery Hills",
"state": "CA",
"zip": "90210",
"price": "319250"
}, {
"h_id": "5",
"city": "New York",
"state": "NY",
"zip": "00010",
"price": "962500"
}
];
如何创建一个函数,仅使用JavaScript按price属性按升序或降序对对象进行排序?
仅对于元素值的普通数组:
function sortArrayOfElements(arrayToSort) {
function compareElements(a, b) {
if (a < b)
return -1;
if (a > b)
return 1;
return 0;
}
return arrayToSort.sort(compareElements);
}
e.g. 1:
var array1 = [1,2,545,676,64,2,24]
output : [1, 2, 2, 24, 64, 545, 676]
var array2 = ["v","a",545,676,64,2,"24"]
output: ["a", "v", 2, "24", 64, 545, 676]
对于对象数组:
function sortArrayOfObjects(arrayToSort, key) {
function compareObjects(a, b) {
if (a[key] < b[key])
return -1;
if (a[key] > b[key])
return 1;
return 0;
}
return arrayToSort.sort(compareObjects);
}
e.g. 1: var array1= [{"name": "User4", "value": 4},{"name": "User3", "value": 3},{"name": "User2", "value": 2}]
output : [{"name": "User2", "value": 2},{"name": "User3", "value": 3},{"name": "User4", "value": 4}]
我最近编写了一个通用函数,如果您想使用它,可以为您管理它。
/**
* Sorts an object into an order
*
* @require jQuery
*
* @param object Our JSON object to sort
* @param type Only alphabetical at the moment
* @param identifier The array or object key to sort by
* @param order Ascending or Descending
*
* @returns Array
*/
function sortItems(object, type, identifier, order){
var returnedArray = [];
var emptiesArray = []; // An array for all of our empty cans
// Convert the given object to an array
$.each(object, function(key, object){
// Store all of our empty cans in their own array
// Store all other objects in our returned array
object[identifier] == null ? emptiesArray.push(object) : returnedArray.push(object);
});
// Sort the array based on the type given
switch(type){
case 'alphabetical':
returnedArray.sort(function(a, b){
return(a[identifier] == b[identifier]) ? 0 : (
// Sort ascending or descending based on order given
order == 'asc' ? a[identifier] > b[identifier] : a[identifier] < b[identifier]
) ? 1 : -1;
});
break;
default:
}
// Return our sorted array along with the empties at the bottom depending on sort order
return order == 'asc' ? returnedArray.concat(emptiesArray) : emptiesArray.concat(returnedArray);
}
使用此函数
const r_sort = (a, b, field, asc) => {
let reverse = asc ? 1 : -1;
if (a[field] > b[field]) {
return 1 * reverse;
}
else if (b[field] > a[field]) {
return -1 * reverse;
}
else {
return 0;
} }
//用法:
homes = homes.sort((a,b) => r_sort(a,b,price,true)) // true for ascending and false for descending