Please provide feedback on my inventory update solution

Here’s my solution to the problem. Feedback welcome :slight_smile:

/**
 * Given an object representation of the inventory,
 * swap the key/value pairs so that the inventory name
 * comes first and the total count is the value.
 */
function swapInventoryKeysForValues(obj) {
  let result = [];

  for (let key in obj) {
    result.push([obj[key], key]);
  }

  return result;
}

/**
 * Sort an inventory array
 */
function sortByInventoryName(a, b) {
  return a[1].localeCompare(b[1], "en", { sensitivity: "base" });
}

/**
 * Update inventory by merging two inventory arrays 
 * and calculating the sum of each inventory item
 */
function updateInventory(arr1, arr2) {
  const allInventory = [...arr1, ...arr2];
  // Step 1: Create an object with all items from both arrays
  let tally = {};

  // Step 2: tally up the numbers for each item
  for (let arr of allInventory) {
    if (tally[arr[1]]) {
      tally[arr[1]] += arr[0];
    } else {
      tally[arr[1]] = arr[0];
    }
  }

  const updatedInventory = swapInventoryKeysForValues(tally).sort(sortByInventoryName);

  return updatedInventory;
}

Hi @JackEdwardLyons !

I created a new post for you.

I have also added [spoiler] tags around your code since this a solution.

Thanks!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.