Reputation: 619
I have two arrays of objects say 1- variants and 2- inventoryLevels. Objects in both arrays share a property which is the id. So I want to search for each variant if it's id is matched with any inventoryLevel I want to change its property named shopify_inventory_quantity with matched inventoryLevel's property available ? My words are little but confusing but take a look at code below basically it's doing properly whats needed I just want to know can it be optimized right now it's nested for loop. So any help to make it efficient would be appreciated ?
for (let i = 0; i < variants.length; i++) {
for (let j = 0; j < inventorylevels.length; j++) {
if (variants[i].id === inventorylevels[j].variant_id) {
variants[i].shopify_inventory_quantity = inventorylevels[j].available;
}
}
}
Upvotes: 0
Views: 64
Reputation: 2771
I understand you have a solution in O(n²)
. Assuming your ids are unique, you can reduce the time complexity to O(n)
(basically what @Alireza commented):
var variants = [
{id: 0, shopify_inventory_quantity: 0},
{id: 1, shopify_inventory_quantity: 0},
{id: 2, shopify_inventory_quantity: 0}
];
var inventoryLevels = [
{id: 0, available: 10},
{id: 1, available: 2},
{id: 2, available: 3}
];
// O(n) + O(n) = O(n)
function getAvailableVariants(v, i) {
// O(n)
var inventoryLevels = i.reduce(function(inventoryLevels, inventoryLevel) {
inventoryLevels[inventoryLevel.id] = inventoryLevel;
return inventoryLevels;
}, {});
// O(n)
return v.map(variant => Object.assign(variant, {shopify_inventory_quantity: inventoryLevels[variant.id].available}));
}
var results = document.createElement('pre');
results.textContent = JSON.stringify(getAvailableVariants(variants, inventoryLevels), null, '\t');
document.body.appendChild(results);
Upvotes: 2