Skip to content

Instantly share code, notes, and snippets.

@ChrisL108
Last active August 15, 2016 04:04
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 ChrisL108/3870d84745c9aa6fe95745f15ab4aff4 to your computer and use it in GitHub Desktop.
Save ChrisL108/3870d84745c9aa6fe95745f15ab4aff4 to your computer and use it in GitHub Desktop.
function updateInventory(arr1, arr2) {
// var newArr = [];
// Reverse array values so that the the
// first values are the names instead of amounts
arr1 = reverseArrayValues(arr1);
arr2 = reverseArrayValues(arr2);
console.log("BEFORE\narr1: "+ arr1 + "\narr2: "+arr2);
// if old array has value from new array
// set the value to the sum of both
// the sum of both values
for (var updated in arr2) {
for (var old in arr1) {
if (arr1[old].indexOf(arr2[updated][0]) !== -1) {
arr1[old][1] += arr2[updated][1];
} else {
arr1.push(arr2[updated]);
}
}
}
console.log("AFTER\narr1: "+ arr1 );
return false;
}
function reverseArrayValues(arr) {
var reversed = arr.reduce(function(all, item) {
all.push([item[1], item[0]]);
return all;
},[]);
//return reversed;
}
updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"],
[1, "Hair Pin"], [5, "Microphone"]],
[[2, "Hair Pin"], [3, "Half-Eaten Apple"],
[67, "Bowling Ball"], [7, "Toothpaste"]]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment