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

json返回数据排序
现有返回json数据

[
  {a: "10",b: "1"},
  {a: "10",b: "0"},
  {a: "10",b: "2"},
  {a: "8",b: "2"},
  {a: "8",b: "0"},
  {a: "4",b: "1"},
  {a: "4",b: "0"},
  {a: "4",b: "3"},
  {a: "4",b: "0"},
  {a: "0",b: "1"},
  {a: "0",b: "2"},
  {a: "0",b: "0"}
]

现在我想他变成这样的排序

[
  {a: "10",b: "0"},
  {a: "10",b: "1"},
  {a: "10",b: "2"},
  {a: "8",b: "0"},
  {a: "8",b: "2"},
  {a: "4",b: "0"},
  {a: "4",b: "0"},
  {a: "4",b: "1"},
  {a: "4",b: "3"},
  {a: "0",b: "0"},
  {a: "0",b: "1"},
  {a: "0",b: "2"}
]

请各位帮帮忙谢谢!

------解决方案--------------------
JScript code
var data  = [
  {a: "10",b: "1"},
  {a: "10",b: "0"},
  {a: "10",b: "2"},
  {a: "8",b: "2"},
  {a: "8",b: "0"},
  {a: "4",b: "1"},
  {a: "4",b: "0"},
  {a: "4",b: "3"},
  {a: "4",b: "0"},
  {a: "0",b: "1"},
  {a: "0",b: "2"},
  {a: "0",b: "0"}
];

var obj = {}, ar_key = [], result = [];
for (var i = 0; i < data.length; i ++) (data[i].a in obj) ? obj[data[i].a].push(data[i].b) : obj[data[i].a] = new Array(data[i].b);
for (x in obj) {
    obj[x].sort(sortByASC);
    ar_key.push(x);
}
ar_key.sort(sortByDESC);

for (var i = 0; i < ar_key.length; i ++) {
    for (var j = 0; j < obj[ar_key[i]].length; j ++) result.push({a: ar_key[i], b: obj[ar_key[i]][j]});
}
console.log(result);

function sortByASC(a, b) { return a - b; }
function sortByDESC(a, b) { return b - a; }

------解决方案--------------------
调用数组的sort方法重排序就好了

JScript code
    var d = [
  { a: "10", b: "1" },
  { a: "10", b: "0" },
  { a: "10", b: "2" },
  { a: "8", b: "2" },
  { a: "8", b: "0" },
  { a: "4", b: "1" },
  { a: "4", b: "0" },
  { a: "4", b: "3" },
  { a: "4", b: "0" },
  { a: "0", b: "1" },
  { a: "0", b: "2" },
  { a: "0", b: "0" }];

  d.sort(function (a, b) {
      if (parseInt(a.a,10) > parseInt(b.a)) return -1;
      else if (a.a == b.a) return parseInt(a.b,10) > parseInt(b.b,10) ? 1 : -1;

      return 1;
  });
  for (var i = 0, j = d.length; i < j; i++) {
      document.write(d[i].a + ':' + d[i].b + '<br/>');
  }