JSFiddle - React, Tailwind, and code Playground
JavaScript
var obj = [{id: 1}, {id: 6}, {id:5}];
var sort = [5, 1, 6];
var result = [];
var findObj = function(id){
for (var i = 0; i < obj.length; i++){
if (obj[i].id === id){return obj[i];}
}
return null;
};
for (var pos = 0; pos < sort.length; pos++){
result.push(findObj(sort[pos]));
}
console.log(JSON.stringify(result));
// 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);