I am faced with a challenge involving two arrays. The first array consists of unique IDs:
idArray = ["56f4cf96dd2ca7275feaf802",
"56f4cf96dd2ca7275feaf7b7",
"56f4cf96dd2ca7275feaf805",
"56f4cf96dd2ca7275feaf7ac"]
The second array contains objects, including titles and corresponding IDs:
stories = [{"title": Story2, id = "56f4cf96dd2ca7275feaf7b7"},
{"title": Story4, id = "56f4cf96dd2ca7275feaf7ac"},
{"title": Story1, id = "56f4cf96dd2ca7275feaf802"},
{"title": Story3, id = "56f4cf96dd2ca7275feaf805"}]
I need to figure out a way to sort the second array based on the index order in the first array. This task is ideally performed using lodash due to possible scalability issues with larger arrays.
So far, I have attempted to extract indexes from the first array as follows:
var sortArray = _.toPairs(idArray)
[ [ '0', 56f4cf96dd2ca7275feaf802 ],
[ '1', 56f4cf96dd2ca7275feaf7b7 ],
[ '2', 56f4cf96dd2ca7275feaf805 ],
[ '3', 56f4cf96dd2ca7275feaf7ac ] ]
Despite experimenting with various combinations of _.map() and _.sortBy(), I'm unable to achieve the desired result which is:
desiredResult = [{"title": Story1, id = "56f4cf96dd2ca7275feaf802"},
{"title": Story2, id = "56f4cf96dd2ca7275feaf7b7"},
{"title": Story3, id = "56f4cf96dd2ca7275feaf805"},
{"title": Story4, id = "56f4cf96dd2ca7275feaf7ac"}]