Monday, 17 April 2017

Sort an array in javascript based on another array

I have an array of Mongoose ID's as follows:

       var ids =[
        mongoose.Types.ObjectId('58c2871414cd3d209abf4fc1'), 
        mongoose.Types.ObjectId('58c2871414cd3d209abf4fc0'),  
        mongoose.Types.ObjectId('58c2871414cd3d209abf5fc0')
      ];

When I call my Mongoose function to get the subdocuments that match these ids, the objects are returned to me in order of how they are found in the database. Can I reorder these based on the order of the above 'ids' array?

The data returned to me is as follows:

 [ { _id: 58c2871414cd3d209abf5fc9,
        companyname: 'Dell',
        position: 
         { _id: 58c2871414cd3d209abf5fc0,
           title: 'Software Engineer',
           location: 'Waterford',
           start: 'May 2017',
           term: 6,
           description: ' Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis erat vitae dsit amet, consectetur adipiscing elit. Vivamus quis erat vitae dolor tempus euismod non in mi' },
      { _id: 58ca9fd6588205e9c8f01431,
        companyname: 'Google',
        position: 
         { _id: 58c2871414cd3d209abf4fc0,
           title: 'Software Engineer',
           location: 'Waterford',
           start: 'May 2017',
           term: 6,
           description: ' Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis erat vitae dsit amet, consectetur adipiscing elit. Vivamus quis erat vitae dolor tempus euismod non in mi' },

      { _id: 58ca9fd6588205e9c8f01431,
        companyname: 'Google',
        position: 
         { _id: 58c2871414cd3d209abf4fc1,
           title: 'Software Engineer',
           location: 'Waterford',
           start: 'June 2017',
           term: 12,
           description: ' Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis erat vitae dsit amet, consectetur adipiscing elit. Vivamus quis erat vitae dolor tempus euismod non in mi' },
 ]

Is there any way of re-ordering these based on the original array? Note there are two _ids returned in the array, its the id for the position sub-document that I need to order. Really stuck if anyone could help that would be great!



via user

No comments:

Post a Comment