0

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;
    }
  }
}
1
  • 3
    You need to give some sample data for better understanding but for what it's worth, the general approach in these situations is to trade space for time. This helps especially if you need to do the search many times and some preparation of data is worth the trouble. What you do is to create a hashmap for lookup, reducing the time complexity to O(n). Commented Aug 16, 2019 at 11:08

1 Answer 1

2

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.