I don't know if this is a peculiar case, but the problem is quite simple at hand. Let's say you have an array which defines the order in which your objects must be sorted. Let's say this array is like this one:
var sort = [5, 1, 6];
This array order is arbitrary (the numbers aren't sorted according to any specific rule), and the sorted array of objects must follow the order in which the items in the sort
array appear)
And you have an array of objects, like this one:
var obj = [{id: 1}, {id: 6}, {id:5}];
So the result (according to the order in sort
and the value of each object's id), should be this:
obj = [{id: 5}, {id: 1}, {id:6}];
I have tried this approach:
var obj = [{id: 1}, {id: 6}, {id:5}];
var sort = [5, 1, 6];
var indexedObjArr = [],
tmpObj = {};
obj.forEach(function(item) {
tmpObj[item.id] = item;
indexedObjArr.push(tmpObj);
tmpObj = {};
});
obj = [];
//This is where it fails, obj ends up having all undefined entries
indexedObjArr.forEach(function(item, i) {
// [sort[i]] === undefined, but sort[i] gives an actual number (e.g. 5),
// and, for instance item[5], gives back the correct item
obj.push(item[sort[i]]);
});
console.log(obj);
What am I doing wrong in this script? Or can you think of a better approach to the problem?
Thank you.