日期:2014-05-16  浏览次数:20273 次

如何把object做排列(依string)?
如果N个object中有几个数值,

example:
OBJ1 {id:1,name:Boss,money:5000}
OBJ2 {id:2,name:Student,money:2000}
OBJ3 {id:3,name:Mon,money:10000}

我要依照name把这些object重新排列,
排成:
OBJ1 {id:1,name:Boss,money:5000}
OBJ3 {id:3,name:Mon,money:10000}
OBJ2 {id:2,name:Student,money:2000}

这样要如何利用.sort去做排列呢?
sort object javascript array

------解决方案--------------------

var example = [
{id:1,name:"Boss",money:5000},
{id:2,name:"Student",money:2000},
{id:3,name:"Mon",money:10000}
]
example = example.sort(function(a,b){
return a.name > b.name?1:-1;
});
for(var i=0, l = example.length; i < l; ++i)
{
document.write(example[i].name+" ");
}


------解决方案--------------------
function createComparisonFunction(propertyName) {

return function(object1, object2) {
var value1 = object1[propertyName];
var value2 = object2[propertyName];

if(value1 < value2) {
return -1;
} else if (value1 > value2) {
return 1;
} else {
return 0;
}
};
}
[{id:1,name:Boss,money:5000}, {id:3,name:Mon,money:10000}, {id:3,name:Mon,money:10000}].sort.createComparisonFunction('name');
------解决方案--------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>无标题页</title>
<script src="linqjs/linq.js" type="text/javascript"></script>
<script type="text/javascript">
//linq.js 请在 http://linqjs.codeplex.com/ 下载
//虽然加了一个js文件, 但非常有用, 以后有什么改动也很方便

var arr = [
{id:1,name:"a",money:5000},
{id:2,name:"c",money:2000},
{id:3,name:"b",money:10000}
  ];
//下面的 newArr 即为所求。
var newArr = Enumerable.From(arr).OrderBy("$.name").ToArray();
</script>
</head>
<body>
<div>&nbsp;</div>
</body>
</html>