Algorithms: Inventory Update
This commit is contained in:
		
							parent
							
								
									063d89f0d8
								
							
						
					
					
						commit
						ecad95a4e8
					
				
							
								
								
									
										40
									
								
								Algorithms/inventoryUpdate.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										40
									
								
								Algorithms/inventoryUpdate.js
									
									
									
									
									
										Normal file
									
								
							@ -0,0 +1,40 @@
 | 
			
		||||
// https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/inventory-update
 | 
			
		||||
 | 
			
		||||
function updateInventory(arr1, arr2) {
 | 
			
		||||
  const inventory = {};
 | 
			
		||||
  arr1.forEach(([quantity, item]) => {
 | 
			
		||||
    inventory[item] = quantity;
 | 
			
		||||
  });
 | 
			
		||||
  arr2.forEach(([quantity, item]) => {
 | 
			
		||||
    if (inventory[item]) {
 | 
			
		||||
      inventory[item] += quantity;
 | 
			
		||||
    } else {
 | 
			
		||||
      inventory[item] = quantity;
 | 
			
		||||
    }
 | 
			
		||||
  });
 | 
			
		||||
  const inventoryArr = [];
 | 
			
		||||
  for (const [item, quantity] of Object.entries(inventory)) {
 | 
			
		||||
    inventoryArr.push([quantity, item]);
 | 
			
		||||
  }
 | 
			
		||||
  inventoryArr.sort(([quantityA, itemA], [quantityB, itemB]) =>
 | 
			
		||||
    itemA > itemB ? 1 : -1
 | 
			
		||||
  );
 | 
			
		||||
  return inventoryArr;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
console.log(
 | 
			
		||||
  updateInventory(
 | 
			
		||||
    [
 | 
			
		||||
      [21, "Bowling Ball"],
 | 
			
		||||
      [2, "Dirty Sock"],
 | 
			
		||||
      [1, "Hair Pin"],
 | 
			
		||||
      [5, "Microphone"],
 | 
			
		||||
    ],
 | 
			
		||||
    [
 | 
			
		||||
      [2, "Hair Pin"],
 | 
			
		||||
      [3, "Half-Eaten Apple"],
 | 
			
		||||
      [67, "Bowling Ball"],
 | 
			
		||||
      [7, "Toothpaste"],
 | 
			
		||||
    ]
 | 
			
		||||
  )
 | 
			
		||||
);
 | 
			
		||||
		Loading…
	
		Reference in New Issue
	
	Block a user