I have these arrays:
Array 1:
const arr1 = [
{_id: "13", qtde: 1, color: "red", size: "100x100"},
{_id: "16", qtde: 5, color: "green", size: "200x200"},
{_id: "1", qtde: 3, color: "yellow", size: "300x300"},
{_id: "23", qtde: 2, color: "purple", size: "500x500"},
{_id: "3", qtde: 0, color: "orange", size: "200x200"}
]
Array 2:
const arr2 = [
{_id: "23", name: "Produto-23", price: "48.99"},
{_id: "13", name: "Produto-13", price: "58.99"},
{_id: "3", name: "Produto-3", price: "58.99"},
{_id: "1", name: "Produto-1", price: "58.99"},
{_id: "16", name: "Produto-16", price: "58.99"}
]
Expected Output:
const arr2 = [
{_id: "13", name: "Produto-13", price: "58.99"},
{_id: "16", name: "Produto-16", price: "58.99"},
{_id: "1", name: "Produto-1", price: "58.99"},
{_id: "23", name: "Produto-23", price: "48.99"},
{_id: "3", name: "Produto-3", price: "58.99"}
]
As can be seen they are different but they have the property _id
in common, but not in the same order. What I want to do is reorganize the second array to have the same order as the first one based on its property _id
.
Just to be clear, I don't want to merge the arrays or change anything besides the order of the second one.
I thought about using Array.sort
, but since I don't have a property of reference I don't know how it could be applied here. The basic idea is to use the index of the first array as reference, since it won't change, but I don't know how as well.
How could I do that?