0

我有表单的 JSON 对象

[
    {
        "Var1": "text1",
        "var2": "text2",
        "var3": "text3",
        "Saving": "integer1"
    },
    {
        "Var1": "text11",
        "var2": "text22",
        "var3": "text33",
        "Saving": "integer2"
    },
    {
        "Var1": "text111",
        "var2": "text222",
        "var3": "text333",
        "Saving": "text"
    }
]

JSON 的“保存”变量包含文本和整数。我想对 JSON 进行排序,以便以最大整数值保存是顶部跟随的文本。我正在使用 javascript

4

3 回答 3

3
[
    {
        "Var1": "text1",
        "var2": "text2",
        "var3": "text3",
        "Saving": "a7"
    },
    {
        "Var1": "text11",
        "var2": "text22",
        "var3": "text33",
        "Saving": 2
    },
    {
        "Var1": "text111",
        "var2": "text222",
        "var3": "text333",
        "Saving": "n3"
    }
].sort(function(a,b){
    var aNum = parseInt(a.Saving, 10);
    var bNum = parseInt(b.Saving, 10);
    if(isNaN(aNum) && isNaN(bNum)){
        return a.Saving > b.Saving;
    }
    if(isNaN(aNum)){
     return true;
    }
    if(isNaN(bNum)){
        return false;
    }
    return aNum > bNum;
});

JSBIN

于 2013-08-20T16:17:42.367 回答
2

You can use lodash's sortBy method: http://lodash.com/docs#sortBy

_.sortBy([1, 2, 3], function(num) { return Math.sin(num); }); // → [3, 1, 2]

_.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math); // → [3, 1, 2]

// using "_.pluck" callback shorthand _.sortBy(['banana', 'strawberry', 'apple'], 'length'); // → ['apple', 'banana', 'strawberry']

If you aren't able to include lodash, please see their source here for how to implement: https://github.com/bestiejs/lodash/blob/master/lodash.js

function sortBy(collection, callback, thisArg) {
  var index = -1,
      length = collection ? collection.length : 0,
      result = Array(typeof length == 'number' ? length : 0);

  callback = lodash.createCallback(callback, thisArg, 3);
  forEach(collection, function(value, key, collection) {
    var object = result[++index] = getObject();
    object.criteria = callback(value, key, collection);
    object.index = index;
    object.value = value;
  });

  length = result.length;
  result.sort(compareAscending);
  while (length--) {
    var object = result[length];
    result[length] = object.value;
    releaseObject(object);
  }
  return result;
}
于 2013-08-20T16:00:46.537 回答
1

Array 的元素可以通过 Array.Sort 方法进行排序。您可以将自定义函数传递给该方法,以按其元素的任何属性对其进行排序。

于 2013-08-20T16:03:19.517 回答