Tell us what’s happening:
Why isn’t my code working ? I don’t have a clue
I’m kindly asking for an explanation if anyone knows why.
Thanks
Your code so far
function updateInventory(arr1, arr2) {
arr2.forEach(function addStock(product) {
for (let i = 0; i <= arr1.length; i++) {
if (product[1] === arr1[i][1]) {
return arr1[i].splice(0,1, arr1[i][0] + product[0]);
} else {
return arr1.push(product)
}
}
})
return arr1;
}
// 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:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/116.0
Challenge: Algorithms - Inventory Update
Link to the challenge:
minor formatting fixes
function updateInventory(arr1, arr2) {
arr2.forEach(function addStock(product) {
for (let i = 0; i <= arr1.length; i++) {
if (product[1] === arr1[i][1]) {
return arr1[i].splice(0, 1, arr1[i][0] + product[0]);
} else {
return arr1.push(product)
}
}
})
return arr1;
}
This mix of functional and imperative is hard to read.
If you look at the output of your sample function call, you have
[ [ 88, 'Bowling Ball' ],
[ 2, 'Dirty Sock' ],
[ 1, 'Hair Pin' ],
[ 5, 'Microphone' ],
[ 2, 'Hair Pin' ],
[ 3, 'Half-Eaten Apple' ],
[ 7, 'Toothpaste' ] ]
It looks like your code isn’t combining entries as its supposed to.
1 Like
arr2.forEach(function(){
for(...){
if(...){
return arr1[i].splice(0,1, arr1[i][0] + product[0]);
} else {
return arr1.push(product)
}
})
Your arr2 item do not loop over arr1 item completely… seems like an early return. So the checking only happens on first item of arr1 every time.
You can add index like “j” to your callback function in forEach() to console log later …
arr2.forEach(function addStock(product, j) {
for(let i = 0; ...){
console.log(j, i)
}
Thanks for taking the time, I’ll log this in the console and take a closer look
system
Closed
5
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.