Search This Blog

2024/04/04

Javascript Interview Question:Inventory Update (FreeCodeCamp)


Compare and update the inventory stored in a 2D array against a second 2D
array of a fresh delivery. Update the current existing inventory item
quantities (in arr1). If an item cannot be found, add the new item and
quantity into the inventory array. The returned inventory array should
be in alphabetical order by item.
where the input is as follows

var currrentInventory = [
[21, "Bowling Ball"],
[2, "Dirty Sock"],
[1, "Hair Pin"],
[5, "Microphone"],
];

var newInventory = [
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"],
];

Expected Output:
[
[ 88, 'Bowling Ball' ],
[ 2, 'Dirty Sock' ],
[ 3, 'Hair Pin' ],
[ 3, 'Half-Eaten Apple' ],
[ 5, 'Microphone' ],
[ 7, 'Toothpaste' ]
]

Solution:

function updateInventory(curInv, newInv) {
newInv.forEach((newElement) => {
let found = curInv.some((oldElement) => {
if (oldElement[1] == newElement[1]) {
oldElement[0] = oldElement[0] + newElement[0];
return true;
}
});
if (!found) {
curInv.push([newElement[0], newElement[1]]);
}
});

//returned inventory array should be in alphabetical order
curInv.sort((a, b) => {
const nameInA = a[1].toLowerCase();
const nameInB = b[1].toLowerCase();

if (nameInA < nameInB) {
return -1;
} else if (nameInA > nameInB) {
return 1;
} else {
return 0;
}
});
return curInv;
}

// 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"],
];

let result = updateInventory(curInv, newInv);
console.log(result);

Output:
[
[ 88, 'Bowling Ball' ],
[ 2, 'Dirty Sock' ],
[ 3, 'Hair Pin' ],
[ 3, 'Half-Eaten Apple' ],
[ 5, 'Microphone' ],
[ 7, 'Toothpaste' ]
]

No comments:

Post a Comment