Last active
August 15, 2016 04:04
-
-
Save ChrisL108/3870d84745c9aa6fe95745f15ab4aff4 to your computer and use it in GitHub Desktop.
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(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