Hi everyone!
I’m having some issues with my code, and I’m trying to understand why forEach pushes all the arr2 plus more when it’s kind of shouldn’t…?? or should??
Here is the output without sort:
[[88, "Bowling Ball"], [ 2, "Dirty Sock"], [3, "Hair Pin"], [5, "Microphone"], [2, "Hair Pin"], [3, "Half-Eaten Apple"], [7, "Toothpaste"], [2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"], [2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]
Your code so far
function updateInventory(arr1, arr2) {
// All inventory must be accounted for or you're fired!
arr1.forEach(function(elem){
arr2.forEach(function(item){
if(elem[1]!==item[1]){
arr1.push(item);
}else{
elem[0]+=item[0];
}
});
});
//console.log(arr1);
return arr1.sort(function(a, b){
return a[1] > b[1];
});
}
// 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);
Your browser information:
Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36
.
Link to the challenge:
https://www.freecodecamp.org/challenges/inventory-update