I need to populate array of ids with objects. In other words I have. Array of ids:
var orderArray = ["5ace454a2b22e17597d0e694", "5acde7c0f7d2520e3b205971", "5ad2086bf05ad342dc723ea1"]
And array of objects:
var objectsArray = [ { _id: 5acde7c0f7d2520e3b205971, name: 'Dinner', restaurant: 5a68d8ea17d9e4308e6400c3, created: 2018-04-11T10:47:28.957Z, status: true, products: [ [Object] ] }, { _id: 5ace454a2b22e17597d0e694, name: 'Test', restaurant: 5a68d8ea17d9e4308e6400c3, image: { _id: 5ad23ed177bcd07303f62899, filename: 'rJKCR2k2f-1523728081111.jpeg', destination: 'images', binded: true }, created: 2018-04-11T17:26:34.186Z, status: false, products: [ [Object], [Object] ] }, { _id: 5ad2086bf05ad342dc723ea1, name: 'Test', restaurant: 5a68d8ea17d9e4308e6400c3, image: null, created: 2018-04-14T13:55:55.449Z, status: true, products: [] } ]
Either you can sort array of objects based on ids… Or map array of ids to array of objects. Probably I’d prefer the second option. But my approach just doesn’t work
orderArray.map(id => objectsArray.filter(obj => obj._id == id))
The result shall be: objectsArray is sorted as order of elements in orderArray
SOLUTION: I’ve opened this question few days ago: Merging 2 arrays with different value types
Here I have the same problem. orderArray is array of objects (not string) thus in order to make it work I need to apply the solution I found earlier (both Array.filter and Array.find functions works well): but in my way it will work only if:
order_array.map(String).map(e => objectsArray.find(a => a._id == e)) //as well as order_array.map(String).map(e => objectsArray.filter(a => a._id == e))
Advertisement
Answer
map
the first array to fill it with corresponding elements from the second one :
var orderArray = ["5ace454a2b22e17597d0e694", "5acde7c0f7d2520e3b205971", "5ad2086bf05ad342dc723ea1"] var objectsArray = [ { _id: '5acde7c0f7d2520e3b205971', name: 'Dinner', restaurant: '5a68d8ea17d9e4308e6400c3', created: '2018-04-11T10:47:28.957Z', status: true, products: [ [Object] ] }, { _id: '5ace454a2b22e17597d0e694', name: 'Test', restaurant: '5a68d8ea17d9e4308e6400c3', image: { _id: '5ad23ed177bcd07303f62899', filename: 'rJKCR2k2f-1523728081111.jpeg', destination: 'images', binded: true }, created: '2018-04-11T17:26:34.186Z', status: false, products: [ [Object], [Object] ] }, { _id: '5ad2086bf05ad342dc723ea1', name: 'Test', restaurant: '5a68d8ea17d9e4308e6400c3', image: null, created: '2018-04-14T13:55:55.449Z', status: true, products: [] } ] var sorted = orderArray.map((e) => { return objectsArray.find((a) => { return a._id == e})}) console.log(sorted)