javascript - JavaScript对象数组的排序

  显示原文与译文双语对照的内容

我使用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 属性以升序和降序顺序表示什么?

时间:

下面是一个更灵活的版本,它允许你创建可以重用的排序函数,并按任何字段排序。


var sort_by = function(field, reverse, primer){

 var key = primer? 
 function(x) {return primer(x[field])} : 
 function(x) {return x[field]};

 reverse =!reverse? 1 : -1;

 return function (a, b) {
 return a = key(a), b = key(b), reverse * ((a> b) - (b> a));
 } 
}

现在你可以按任意字段排序。。


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"

}];

//Sort by price high to low
homes.sort(sort_by('price', true, parseInt));

//Sort by city, case-insensitive, A-Z
homes.sort(sort_by('city', false, function(a){return a.toUpperCase()}));

要对它进行排序,你需要创建一个带有两个参数的比较器函数,然后使用比较函数调用排序函数,如下所示:


//a and b are object elements of your array
function mycomparator(a,b) {
 return parseInt(a.price) - parseInt(b.price);

}

如果你想升序排序 parseInt(a.price) - parseInt(b.price)parseInt(b.price) - parseInt(a.price) 注意从a 到b的变化。

进行排序


homes.sort(mycomparator);

你想用Javascript对它的进行排序,对吧? 你想要的是 sort() 函数 。 在这种情况下,你需要编写一个比较器函数并将它的传递给 sort(),这样就可以:


function comparator(a, b) {
 return parseInt(a["price"]) - parseInt(b["price"]);
}

var json = {"homes": [/* your previous data */] };
console.log(json["homes"].sort(comparator));

你的比较器接受数组中每个嵌套哈希的一个,并通过检查"价格"字段决定哪个是更高的。

对于字符串排序,以防有人需要它,


var dataArr = { 

"hello": [{
"id": 114,
"keyword":"zzzzzz",
"region":"Sri Lanka",
"supportGroup":"administrators",
"category":"Category2"
}, {
"id": 115,
"keyword":"aaaaa",
"region":"Japan",
"supportGroup":"developers",
"category":"Category2"
}]

};
var sortArray = dataArr['hello'];
sortArray.sort(function(a,b) {
 if ( a.region <b.region )
 return -1;
 if ( a.region> b.region )
 return 1;
 return 0;
} );

这是上面所有答案的一个顶点。

篡改验证:http://jsfiddle.net/bobberino/4qqk3/


var sortOn = function (arr, prop, reverse, numeric) {

//Ensure there's a property
 if (!prop ||!arr) {
 return arr
 }

//Set up sort function
 var sort_by = function (field, rev, primer) {

//Return the required a,b function
 return function (a, b) {

//Reset a, b to the field
 a = primer(a[field]), b = primer(b[field]);

//Do actual sorting, reverse as needed
 return ((a <b)? -1 : ((a> b)? 1 : 0)) * (rev? -1 : 1);
 }

 }

//Distinguish between numeric and string to prevent 100's from coming before smaller
//e.g.
//1
//20
//3
//4000
//50

 if (numeric) {

//Do sort"in place" with sort_by function
 arr.sort(sort_by(prop, reverse, function (a) {

//- Force value to a string.
//- Replace any non numeric characters.
//- Parse as float to allow 0.02 values.
 return parseFloat(String(a).replace(/[^0-9.-]+/g, ''));

 }));
 } else {

//Do sort"in place" with sort_by function
 arr.sort(sort_by(prop, reverse, function (a) {

//- Force value to string.
 return String(a).toUpperCase();

 }));
 }


}

我还使用了某种分级和多个字段排序:


arr = [
 {type:'C', note:834},
 {type:'D', note:732},
 {type:'D', note:008},
 {type:'F', note:474},
 {type:'P', note:283},
 {type:'P', note:165},
 {type:'X', note:173},
 {type:'Z', note:239},
];

arr.sort(function(a,b){ 
 var _a = ((a.type==='C')?'0':(a.type==='P')?'1':'2');
 _a += (a.type.localeCompare(b.type)===-1)?'0':'1';
 _a += (a.note>b.note)?'1':'0';
 var _b = ((b.type==='C')?'0':(b.type==='P')?'1':'2');
 _b += (b.type.localeCompare(a.type)===-1)?'0':'1';
 _b += (b.note>a.note)?'1':'0';
 return parseInt(_a) - parseInt(_b);
});

结果


[
 {"type":"C","note":834},
 {"type":"P","note":165},
 {"type":"P","note":283},
 {"type":"D","note":8},
 {"type":"D","note":732},
 {"type":"F","note":474},
 {"type":"X","note":173},
 {"type":"Z","note":239}
]

你可以在回调函数中使用 JavaScript sort 方法:


function compareASC(homeA, homeB)
{
 return parseFloat(homeA.price) - parseFloat(homeB.price);
}

function compareDESC(homeA, homeB)
{
 return parseFloat(homeB.price) - parseFloat(homeA.price);
}

//Sort ASC
homes.sort(compareASC);

//Sort DESC
homes.sort(compareDESC);

要对数组进行排序,必须定义比较器函数。 这里函数在你所需的排序模式或者顺序上总是不同的( 例如 。 升序或者降序。

创建一些函数,这些函数对数组进行升序或者降序排序,其中包含对象或者字符串或者数字值。


function sorterAscending(a,b) {
 return a-b;
}

function sorterDescending(a,b) {
 return b-a;
}

function sorterPriceAsc(a,b) {
 return parseInt(a['price']) - parseInt(b['price']);
}

function sorterPriceDes(a,b) {
 return parseInt(b['price']) - parseInt(b['price']);
}

排序编号( 按字母顺序和升序):


var fruits = ["Banana","Orange","Apple","Mango"];
fruits.sort();

排序编号( 按字母顺序和降序):


var fruits = ["Banana","Orange","Apple","Mango"];
fruits.sort();
fruits.reverse();

排序编号( 数字和升序):


var points = [40,100,1,5,25,10];
points.sort(sorterAscending());

排序编号( 数字和降序):


var points = [40,100,1,5,25,10];
points.sort(sorterDescending());

就像上面使用的sorterPriceAsc和sorterPriceDes方法,你的数组具有所需的键。


homes.sort(sorterPriceAsc()) or homes.sort(sorterPriceDes())

...