Reordering an Array Based on Another Array’s Order in Javascript
So I had a problem, awhile ago, where I needed to reorder elements in an array based off of the order of another array. So I basically had to capture the order from one and apply it to another. In my case, both arrays had a common id field. However, with the model I have here, I was able to order additional arrays without the id field, if I needed to, which I did 🙂
Below is my code solution.
function getNewOrder() { //Get an identifier from the array you want to base the order on const newIds = newArrayOrder.map(x => x.id); //Get an identifier from the array you want to update const ids = arrayToOrder.map(x => x.id); //placeholder for order const order = []; //loop through the ids, pushing the arrayToOrder's index of the new order ids //We end up with an array of indexes for(let i = 0; i < ids.length; i++) { order.push(ids.indexOf(newIds[i])); } //reorder the array reorderIds(order, arrayToOrder); } //Preform the reordering function reorderIds(order, arrayToOrder){ //Get a copy of the array we want to change const temp = arrayToOrder.slice(0); //loop through the indexes //use the indexes to place the items in the right place from the copy into the original for(let i = 0; i < arrayToOrder.length; i++) { arrayToOrder[order[i]] = temp[i]; } }