Skip to content Skip to sidebar Skip to footer

Sorting Nested Objects Using Javascript And/or Underscore.js

I'm having trouble sorting an object by TearSheetTypeName and StartDate using Javascript or Underscore.js. The object looks like this: { Components: {141: {TearSheetTypeName: '

Solution 1:

It seems like Components should be an array. With that precondition, your object would look like this:

{
  Components: [
    {Id: 141, TearSheetTypeName: "Skyscraper", StartDate: "2015-01-01"},
    {Id: 142, TearSheetTypeName: "Skyscraper", StartDate: "2015-01-01"},
    {Id: 145, TearSheetTypeName: "New Car", StartDate: "2015-01-15"},
    {Id: 146, TearSheetTypeName: "New Car", StartDate: "2015-01-01"}
  ]
}

Then you don't even need underscore to sort Components. The native Array.prototype.sort works just as well (and if you look at the underscore source, is actually used by_.sortBy().

data.sort(function(a,b){

    if(a.TearSheetTypeName > b.TearSheetTypeName){
      return1;
    }

    if(a.TearSheetTypeName < b.TearSheetTypeName){
      return -1;
    }

    //if we got this far, the strings are the same, so sort by dateif(newDate(a.StartDate) > newDate(b.Startdate)) {
    return1;
    }

    if(newDate(a.StartDate) < newDate(b.Startdate)) {
    return -1;
    }

    //if we got this far, the criteria is the samereturn0;
});

The sort happens in place, so you don't need to assign it.

Post a Comment for "Sorting Nested Objects Using Javascript And/or Underscore.js"