I have an array of objects called posts with a nested field answer. I have different conditions depending on which I need to sort my array.
Example array
let posts = [ { "_id": "610b806ec6386ffa276b6d1c", "post": "CDat the difference between Equity and News channel?", "answers": [ { "_id": "613724604dd4b6f39b344b4c", "type": "text", }, { "_id": "6113c826a64da80fe48ab543", "type": "video", }, { "_id": "6113c740a64da80fe48ab534", "type": "audio", }, { "_id": "611135cf7497d70b6cc2c5e0", "type": "video", } ] }, { "_id": "611e14329ff0c343540ae10e", "post": "How forex affects investment 6", "answers": [ { "_id": "61371b3a9bf14a39207fff8a", "type": "video", }, { "_id": "613719369507fd12f93e3c62", "type": "text", }, { "_id": "6135f28e29aeae3de45fc8c2", "type": "text", }, { "_id": "6135f07c831da33c28fc1cf6", "type": "audio", }, { "_id": "6135eb2d51a8830698d65cf3", "type": "text", }, ] } ]
What I need to do is…I want to sort all the answers with type “video” to start and after that type “audio” and then type “text” answers like so
let posts = [ { "_id": "610b806ec6386ffa276b6d1c", "post": "CDat the difference between Equity and News channel?", "answers": [ { "_id": "613724604dd4b6f39b344b4c", "type": "video", }, { "_id": "6113c826a64da80fe48ab543", "type": "video", }, { "_id": "6113c740a64da80fe48ab534", "type": "audio", }, { "_id": "611135cf7497d70b6cc2c5e0", "type": "text", } ] }, { "_id": "611e14329ff0c343540ae10e", "post": "How forex affects investment 6", "answers": [ { "_id": "61371b3a9bf14a39207fff8a", "type": "video", }, { "_id": "613719369507fd12f93e3c62", "type": "audio", }, { "_id": "6135f28e29aeae3de45fc8c2", "type": "text", }, { "_id": "6135f07c831da33c28fc1cf6", "type": "text", }, { "_id": "6135eb2d51a8830698d65cf3", "type": "text", }, ] } ]
Any help would be appreciated. Thank you
Advertisement
Answer
You will need to loop through each entry in your posts
array and sort the answers
array inside each entry using a custom function.
The return value of the custom function (ele1, ele2) => {}
should return a value > 0 if ele1
should be placed after ele2
, a value < 0 if ele1
should be placed before ele2
, and a value = 0 if they are considered equal.
const getRanking = (ele) => { if (ele.type == "video") return 1; if (ele.type == "audio") return 2; if (ele.type == "text") return 3; }; posts = posts.map(post => { post.answers.sort((ele1, ele2) => { return getRanking(ele1) - getRanking(ele2); }); return post; });