# Algorithms - Inventory Update

Tell us what’s happening:
I’m struggling with this exercise to update the number of an element in a 2 dimensional array.

``````function updateInventory(arr1, arr2) {
for(let i = 0; i<arr2.length; i++){
for(let j = 0; j<arr1.length; j++){
if(arr1[j]!==arr2[i] && j==arr1.length-1){
arr1.push(arr2[i])
}
if(arr1[j]===arr2[i]){
if(arr2[i] > arr1[j] && arr2[i] == arr2[j]){
arr1[j] = arr2[i];
break;
}
else{
break;
}
}
}
}
arr1.sort(function (a, b) {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
})
return arr1;
}
``````

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.63`

Challenge: Algorithms - Inventory Update

What exactly is giving you troubles? Do you get any error?

My problem ist that my array wont get updated soe the number doesnt get changed. It pushes elements from the second array, that weren’t in the first array but it doesnt update the number of an already existing element (e.g. [21, Apple] is in the first array and [40, Apple] in the second so in the first array I’d need to change it to 40 too)

Add the following `console.log` statement before the first `if` statement. I don’t think you understand what is going on with the code you have written.

Also, instructions want to you to add the new inventory to the existing inventory. You are attempting to replace it in your second `if` statement, though you have some other logic issues in that section you need to figure out.

For example, what is the purpose of the following line of code?

``````if (arr2[i] > arr1[j] && arr2[i] == arr2[j]) {
``````

I solved the exercise now with (almost) the same code now.

I thought first that you’d need to compare the two same elements with their quantities but just realized i need to add the quantity. But basically what I did was, check if the quantities differs from each other and add them together if it’s true. I just realized I could just instantly use the arr1[j] += arr2[i] command after every iteration when arr2[i] == arr2[j]

My final code is this

``````function updateInventory(arr1, arr2) {
if(arr1.length == 0){
arr1 = arr1.concat(arr2);
}
for(let i = 0; i<arr2.length; i++){
for(let j = 0; j<arr1.length; j++){
if(arr1[j]!==arr2[i] && j==arr1.length-1){
arr1.push(arr2[i])
}
if(arr1[j]===arr2[i]){
if(arr2[i] > arr1[j]){
arr1[j] += arr2[i];
break;
}
else{
break;
}
}
}
}
arr1.sort(function (a, b) {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
})
return arr1;
}
``````

The reason why I only check if arr1 is empty is because, if arr2 is empty, nothing gets pushed to arr1 and nothing needs to be pushed.
I’m not really satisfied with my solutions, can I optimize my code more or should I just rewrite it? 