Update inventory (review requested)

(please suggest improvements).

Challenge: Compare and update the inventory stored in a 2D array against a second 2D array of a fresh delivery. Update the current existing inventory item quantities (in arr1 ). If an item cannot be found, add the new item and quantity into the inventory array. The returned inventory array should be in alphabetical order by item.

function updateInventory(arr1, arr2) {
     //Nested Function to check if new item is present in current inventory if yes then update current inventory. else return True.
    function itemCheck(a, b){
        let result = true;
     for (let j = 0; j < b.length; j++){
        if (b[j].includes(a[1])){
            b[j][0] += a[0];
           result = false;
        return result;
    // Compare function to arrange alphabetically.
    function compareFunction (a, b){
      return  a[1] === b[1] ? 0: a[1] < b[1] ? -1: 1;

    //Update current inventory
    for (let i = 0; i < arr2.length; i++){
       if (itemCheck(arr2[i], arr1)){
    //Alphabetical order.
    return arr1;

// Example inventory lists
var curInv = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [1, "Hair Pin"],
    [5, "Microphone"]

var newInv = [
    [2, "Hair Pin"],
    [3, "Half-Eaten Apple"],
    [67, "Bowling Ball"],
    [7, "Toothpaste"]

updateInventory(curInv, newInv);

Hi @lethemeer !

I moved your post over to the javascript section.
Code reviews for javascript tend to get more responses in the javascript section than the project feedback section.

Also, I added the link for the challenge you are referring to.

  • Use better variable names.

  • Avoid mutation.

  • Use array methods instead of loops.

  • Separate concerns. You have a itemCheck function that is used for a boolean check but is also causing side effects.

if (itemCheck(arr2[i], arr1)) { 

If I just look at its usage I have no way of knowing that it is also changing data. A function that is used like this should (in my opinion) not have side effects.

1 Like


First I thought to do both tasks in separate functions i.e. change data and Boolean check but in the spirit of keeping my code DRY I kept them in one function.
The expected subtleness in my code is an outcome of experience and advice from seasoned coders like you. Thank you for your input.

Thank you sister. please keep an eye on me.

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