Last active
November 1, 2016 06:31
-
-
Save jampola/45164f92d49c89d58b8976387abb5f7f to your computer and use it in GitHub Desktop.
Inventory update (FreeCodeCamp)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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