Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort nested array of objects

Tags:

I'm looking for a way to sort a nested array of objects.

Here's an example:

{   answers : [     { name : 'paul',  state : 'RU' },     { name : 'steve', state : 'US' },      { name : 'mike',  state : 'DE' },      ...   ] } 

Suppose now I want to find all the name, of the answers array, but how can I sort them in ascending order?

like image 569
Kaylit Avatar asked Sep 14 '12 22:09

Kaylit


People also ask

How do you sort nested array of objects?

// arr is the array of objects, prop is the property to sort by var sort = function (prop, arr) { arr. sort(function (a, b) { if (a[prop] < b[prop]) { return -1; } else if (a[prop] > b[prop]) { return 1; } else { return 0; } }); };

Can you sort an array of objects in JavaScript?

Sort an Array of Objects in JavaScriptTo sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.


1 Answers

I would store it in the order you want it back out. Or sort it after you pull it out, on the client side.

If neither of those are possible, you can use the aggregation framework:

> db.test.insert({answers: [ ...                 {name: 'paul', state: 'RU'}, ...                 {name: 'steve', state: 'US'},  ...                 {name: 'mike', state: 'DE'}]}); > db.test.insert({answers: [ ...                 {name: 'paul', state: 'RU'}, ...                 {name: 'steve', state: 'US'},  ...                 {name: 'xavier', state: 'TX'}]});  db.test.aggregate([   {$unwind: "$answers"},    {$sort: {"answers.name":1}},    {$group: {_id:"$_id", answers: {$push:"$answers"}}} ]); 

produces:

{   "result" : [   {     "_id" : ObjectId("5053b2477d820880c3469364"),     "answers" : [       {         "name" : "paul",         "state" : "RU"       },       {         "name" : "steve",         "state" : "US"       },       {         "name" : "xavier",         "state" : "TX"       }     ]   },   {     "_id" : ObjectId("5053af9f7d820880c3469363"),     "answers" : [       {         "name" : "mike",         "state" : "DE"       },       {         "name" : "paul",         "state" : "RU"       },       {         "name" : "steve",         "state" : "US"       }     ]   } ],   "ok" : 1 } 
like image 60
Eve Freeman Avatar answered Sep 23 '22 12:09

Eve Freeman