I am trying to process a JSON object and do maths to calculate a weight. Order matters in my algorithm, but the order of products in the JSON object are passed to me in the order the customer adds them to their cart. I need to sort a number of attributes in the same fashion.
In the following example, a customer has added products in the "wrong" (1.5,1,1.25) order, so object.products looks as such:
"products":[
{
"quantity": 3,
"weight_each": 1.5
},
{
"quantity": 4,
"weight_each": 1
},
{
"quantity": 2,
"weight_each": 1.25
}
My first step is to add these objects to a more keyboard friendly array:
for (var i = 0; i < object.products.length; i++)
{
quantity[i] = object.products[i].quantity;
weight[i] = object.products[i].weight_each;
}
My algorithm, as previously mentioned, requires that products be ordered by weight (ascending). I know how to sort each array independently [weight.sort()], but I do not know how to sort each array so that, post-sort, weight[0] and quantity[0] reference the same product.
My end result should look like so:
console.log(weight) // [1,1.25,1.5]
console.log(quantity) // [4,2,3]
I have google'd many different phrases and tried several different methods. I apologize if this has already been answered, or if this is a rudimentary question. I cannot seem to move past this roadblock on my own, and all answers are greatly appreciated! :)