JSFiddle - React, Tailwind, and code Playground
JavaScript
var oldOrder = [{
id: 4,
name: 'alex'},
{
id: 3,
name: 'jess'},
{
id: 9,
name: '...'},
{
id: 1,
name: 'abc'}];
function sort(array, order) {
//create a new array for storage
var newArray = [];
//loop through order to find a matching id
for (var i = 0; i < order.length; i++) {
//label the inner loop so we can break to it when match found
dance:
for (var j = 0; j < array.length; j++) {
//if we find a match, add it to the storage
//remove the old item so we don't have to loop long nextime
//and break since we don't need to find anything after a match
if (array[j].id === order[i]) {
newArray.push(array[j]);
array.splice(j,1);
break dance;
}
}
}
return newArray;
}
var newOrder = sort(oldOrder,[3, 1, 9, 4]);
console.log(newOrder);