I am attempting to merge a "fresh shipment" array with a current inventory array by first creating object to make the data more manageable. So, any same-items are added to any existing ones in inventory.
.sort runs but flat doesn't seem to do anything. I suspect there is some kind of issues related to how I made the array and messing up the indices?
function updateInventory(arr1, arr2) {
let invObj = {}
let updateObj = {}
let result = []
arr1.forEach( x => invObj[x[1]] = x[0])
arr2.forEach( x => updateObj[x[1]] = x[0])
for(let key in updateObj) {
if (invObj[key]) {
invObj[key] += updateObj[key]
} else {
invObj[key] = updateObj[key]
}
}
result = Object.keys(invObj).map(key=>[invObj[key],key])
.sort((a,b)=>{
// attempting to sort inventory alphabetically here as required by my course's test
return a[1] - b[1]
})
return result
}
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"]
];
console.log(updateInventory(curInv, newInv));
localeComparemethod off of the strings.localCompareto compare strings. Your sort test should readreturn a[1].localeCompare(b[1]);