user3789191 user3789191 - 3 months ago 8
Javascript Question

How to Sort Nested Javascript Array

I have an array

var a=[['test':'1','test1':'2','test2':{'test3':'3','test4':'4'}],['test':'2','test1':'2','test2':{'test3':'1','test4':'2'}]];


I can sort array using test and test 1 fields. But I have no idea to sort using test3 or test4. How can this array be sorted.

CODE

[{"HotelId":18,"HotelName":"Trader","HotelAlias":"trader-hotel","HotelStreet":null,"Address":"No.18","HotelDescription":"Near to Shwedagone Pagoda","HotelLat":16.819910049438,"HotelLng":96.130912780762,"CityId":33,"RegionId":1,"Breakfast":1,"Lunch":0,"Dinner":0,"Snack":0,"Wifi":1,"CreatedOn":"2016-08-24 14:09:57","city":{"CityId":33,"CityName":"Bahan","RegionId":1,"CityPostCode":"11210","CityDescription":null,"region":{"RegionId":1,"RegionName":"Yangon","ISO":"MM-06","RegionDescription":"Old Capital of Myanmar"}},"room_count":null,"room_lock_count":null},{"HotelId":17,"HotelName":"Yuzana","HotelAlias":"yuzana-hotel","HotelStreet":null,"Address":"No.18","HotelDescription":"Near to Shwedagone Pagoda","HotelLat":16.819910049438,"HotelLng":96.130912780762,"CityId":33,"RegionId":1,"Breakfast":1,"Lunch":0,"Dinner":0,"Snack":0,"Wifi":1,"CreatedOn":"2016-08-22 17:47:42","city":{"CityId":33,"CityName":"Bahan","RegionId":1,"CityPostCode":"11210","CityDescription":null,"region":{"RegionId":1,"RegionName":"Yangon","ISO":"MM-06","RegionDescription":"Old Capital of Myanmar"}},"room_count":null,"room_lock_count":null},{"HotelId":16,"HotelName":"Strand","HotelAlias":"strand-hotel","HotelStreet":null,"Address":"No.18","HotelDescription":"The river view","HotelLat":16.819910049438,"HotelLng":96.130912780762,"CityId":12,"RegionId":1,"Breakfast":1,"Lunch":0,"Dinner":0,"Snack":1,"Wifi":1,"CreatedOn":"2016-08-22 13:57:27","city":{"CityId":12,"CityName":"Kyauktada","RegionId":1,"CityPostCode":null,"CityDescription":null,"region":{"RegionId":1,"RegionName":"Yangon","ISO":"MM-06","RegionDescription":"Old Capital of Myanmar"}},"room_count":null,"room_lock_count":null},{"HotelId":14,"HotelName":"Novotal","HotelAlias":"novotal-hotel","HotelStreet":null,"Address":"Kamayut","HotelDescription":"The best hotel","HotelLat":16.819910049438,"HotelLng":96.130912780762,"CityId":11,"RegionId":1,"Breakfast":1,"Lunch":0,"Dinner":0,"Snack":1,"Wifi":1,"CreatedOn":"2016-08-22 11:48:35","city":{"CityId":11,"CityName":"Kamayut","RegionId":1,"CityPostCode":null,"CityDescription":null,"region":{"RegionId":1,"RegionName":"Yangon","ISO":"MM-06","RegionDescription":"Old Capital of Myanmar"}},"room_count":{"HotelId":14,"qty":7},"room_lock_count":{"HotelId":14,"qty":7}}]

Answer

This should sort on test3.

a.sort(function (item1, item2) {
  if (item1.test2.test3 < item2.test2.test3) return -1;
  if (item1.test2.test3 > item2.test2.test3) return 1;
  return 0;
});