0

I have JSON object of the form

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

"Saving" variable of the JSON contains both text and integer. I want to sort the JSON such that Saving with maximum integer value is top followed text. I am using javascript

user2129794
  • 2,388
  • 8
  • 33
  • 51

3 Answers3

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

Ray Cheng
  • 12,230
  • 14
  • 74
  • 137
bluetoft
  • 5,373
  • 2
  • 23
  • 26
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;
}
djechlin
  • 59,258
  • 35
  • 162
  • 290
1

Elements of Array can be sorted by Array.Sort method. You can pass a custom function into the method to sort it by any properties of its elements.

Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136