Skip to content

Instantly share code, notes, and snippets.

@jampola
Last active November 1, 2016 06:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jampola/45164f92d49c89d58b8976387abb5f7f to your computer and use it in GitHub Desktop.
Save jampola/45164f92d49c89d58b8976387abb5f7f to your computer and use it in GitHub Desktop.
Inventory update (FreeCodeCamp)
function updateInventory(curArr, newArr) {
// All inventory must be accounted for or you're fired!
// using an object so we can assign k'v values
var curObj = {};
var returnArr = [];
var arr = [];
// add to obj so we can access k,v's
curArr.forEach(function(data){
curObj[data[1]] = data[0]
});
for (var i in newArr){
// if something in the newInv doesn't exist in the curInv, add to it
if(curObj.hasOwnProperty(newArr[i][1]) === false){
curObj[newArr[i][1]] = newArr[i][0];
}
// since we've added the initial values for the items that don't exist
// there is no reason to append them
else {
// append the values
curObj[newArr[i][1]] += newArr[i][0];
}
}
// push the values from our obj to an arr to return
for(var x in curObj){
// console.log(String.charCodeAt(x.toLowerCase()));
returnArr.push([curObj[x],x]);
}
// sort by second col (item text) if larger than next;
returnArr.sort(function(a,b){
return a[1] > b[1];
});
return returnArr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment