javascript - Sorting an array of objects? -


i have following data structure , i'm stuck on way sorting variants items in ascending order based on price.

ideally need way find lowest price of item variant while still having access variant's parent.

var items = [ {     "id" : 1 ,     "name" : "name1",     "variations" : [         {             "subid" : 1000011,             "subname" : "name1a",             "price" : 19.99         },         {             "subid" : 1000012,             "subname" : "name1b",             "price" : 53.21         },         {             "subid" : 1000013,             "subname" : "name1c",             "price" : 9.49          }     ]  }, {     "id" : 2,      "name" : "name2",     "variations" : [         {             "subid" : 1000021,             "subname" : "name2a",             "price" : 99.29         },         {             "subid" : 1000022,             "subname" : "name2b",             "price" : 104.99         },         {             "subid" : 1000023,             "subname" : "name2c",             "price" : 38.00          }     ]  }  ]; 

you can use following code in order it:

items.foreach(function(item){   var variations = item.variations.sort(function(a, b){     return b.price - a.price;   });   console.log(variations); }); 

this function going called every item inside of items array. if want order first, or second or n item in items array need use like:

var variations = items[0].variations.sort(function(a, b){   return b.price - a.price; }); console.log(variations); 

where items[0] represents item want order.

as can see:

function(a, b){   return b.price - a.price; } 

is function orders final result of every array item items array. using the sort function. can read more how compare function works sort items of array.

the array elements sorted according return value of compare function


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -