Hello All. I’ve been working on inventory update for about an hour and I think I am fairly close to a feasible solution. Here is my current code:
function updateInventory(arr1, arr2) {
// All inventory must be accounted for or you're fired!
var x = 0;
var temp = [];
while (x<arr1.length) { // two loops are so it can loop through every element in arr2 through the first element
for(var i = 0; i<arr2.length; i++) { //of arr 1, and then so on.
if(arr1[x].indexOf(arr2[i][1]) > 0) { //checks if the name is already in the array, if so, add inventory
arr1[x][0] += arr2[i][0];
} else if (arr1[x].indexOf(arr2[i][1]) < 0 && //checks if item is already arr 1, if not and not in temp
temp.indexOf(arr2[i]) < 0) { // then the logic puts the element into temp
temp.push(arr2[i]);
}
}
x++; //loops here so that all possible values can be considered.
}
var finalArray = []; //will be worked on after bug
return temp;
}
// 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(curInv, newInv);
My current problem in the code, is that because my two loops loop through every possible element in both arrays,
[21, "Bowling Ball"]
still is put into the temp array. I understand why this is the case, due to my earlier logic statement where if a name from arr22
it is not in that particular element, then it will be added to temp.
I’m looking for a method or a hint of a method in which I can remove all arrays in my temp
array that have a name that is already located in my arr1
Thanks for any help