# 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][1]!==arr2[i][1] && j==arr1.length-1){
arr1.push(arr2[i])
}
if(arr1[j][1]===arr2[i][1]){
if(arr2[i][0] > arr1[j][0] && arr2[i][1] == arr2[j][1]){
arr1[j][0] = arr2[i][0];
break;
}
else{
break;
}
}
}
}
arr1.sort(function (a, b) {
if (a[1] < b[1]) {
return -1;
}
if (a[1] > b[1]) {
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)

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][1] == arr2[j][1]

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][1]!==arr2[i][1] && j==arr1.length-1){
arr1.push(arr2[i])
}
if(arr1[j][1]===arr2[i][1]){
if(arr2[i][0] > arr1[j][0]){
arr1[j][0] += arr2[i][0];
break;
}
else{
break;
}
}
}
}
arr1.sort(function (a, b) {
if (a[1] < b[1]) {
return -1;
}
if (a[1] > b[1]) {
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?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.