-4
{
  "services": [{
    "id": "b1",
    "address": {
      "location_id": "loc_b1",
      "name": "hunupitiya-2",
      "lon": "",
      "lat": ""
    },
    "size": [1700]
  },{
    "id": "b2",
    "address": {
      "location_id": "loc_b2",
      "name": "kelaniya-1",
      "lon":"" ,
      "lat":"" 
    },
    "size": [2889]
  }]
} 

I have a collection of Objects inside an Array, I need to sort this collection of object based on nested object's property name splitting it by "-" (the property I am looking for is the address.name). so the above are 1 and 2 after splitting. So what I am trying to achieve is a function that will return a sorted array of objects like below

{
  "services": [{
    "id": "b2",
    "address": {
      "location_id": "loc_b2",
      "name": "kelaniya-1",
      "lon":"" ,
      "lat":""
    },
    "size": [2889]
  },{
    "id": "b1",
    "address": {
      "location_id": "loc_b1",
      "name": "hunupitiya-2",
      "lon": "",
      "lat": ""
    },
    "size": [1700]
  }]
}

I have like 31 objects, I also have objects without the "-", so I am trying get the numbered once from small to big and then the rest in any order. I have created a jsfiddle to try to work it.

https://jsfiddle.net/cbjosk3g/

Ihsan
  • 5
  • 1

1 Answers1

0

You could use the standard Array#sort with a sort function which splits the value and takes the second part of the array.

var $scope = { services: [{ id: "b1", address: { location_id: "loc_b1", name: "hunupitiya-2", lon: "", lat: "" }, size: [1700] }, { id: "b2", address: { location_id: "loc_b2", name: "kelaniya-1", lon: "", lat: "" }, size: [2889] }] };

$scope.services.sort(function (a, b) {
    return a.address.name.split('-')[1] - b.address.name.split('-')[1];
});

console.log($scope);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392