Coding Interview Prep: Algorithms - Inventory Update (freeCodeCamp)

 Inventory Update

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.


Solution:

function updateInventory(arr1arr2) {
    let newInv = [];

    function getIndex(item) {
        for(let i=0;i<arr1.length;i++){
            if(arr1[i].includes(item)) {
                return i;
            }
        }
        return undefined;
    }

    for(let i=0;i<arr2.length;i++) {
        let j = getIndex(arr2[i][1])
        if(j !== undefined) {
            arr1[j][0] = arr1[j][0] + arr2[i][0]
        } else {
            newInv.push(arr2[i])
        }
    }

    let curInv = arr1.concat(newInv)
    let sortedArr = curInv.sort(function(a,b){
            return a[1].charCodeAt(0)-b[1].charCodeAt(0)
        })
    console.log(sortedArr)
    return sortedArr;
}

// 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(curInvnewInv);



Click here to go to the original link of the question.

Post a Comment

Previous Post Next Post