Inventory Update Sort

I need help understanding why my alphabetical sort is not implemented correctly.

**Your code so far**

function updateInventory(arr1, arr2) {
let newInv = {};
let shipment = arr2;
let result =[];
// populate inventory with arr1 kv pairs
for(let item of arr1){
    newInv[item[1]] = item[0]
}
//update or add items to inventory
for(let item of shipment){
    if(newInv.hasOwnProperty(item[1])){
        newInv[item[1]]+= item[0]
    }else{
        newInv[item[1]] = item[0]
    }
}

//re arrange from k v to  v k pairs
for(let item of Object.entries(newInv)){
result.push([item[1],item[0]])
}
//This will not sort alphabetically
result.sort((a,b)=>a[1]-b[1])

//niether will this
// result.sort((a,b)=>a[1][0] - b[1][0])

// this works to sort by quantity ascending
// result.sort((a,b)=>a[0]-b[0])

console.log(result)

return result;
}

updateInventory([[0, "Bowling Ball"], [0, "Dirty Sock"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]])

**Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:100.0) Gecko/20100101 Firefox/100.0

Challenge: Inventory Update

Link to the challenge:

All the sorting comparisons you’re showing are sorting by performing math, but when dealing with strings, the result won’t really work. You might try something expressly made for comparing strings: DevDocs

1 Like

Thank you. I was able to solve by changing:

result.sort((a,b)=>a[1]-b[1])

To:

result.sort((a,b)=>a[1]>b[1])

edit:
this also works

 result.sort((a,b)=>a[1].localeCompare(b[1]))
1 Like

The only real issue with using

result.sort((a,b) => a[1]>b[1])

Is that if a[1]==="foo" and b[1]==="Foo", *they are not the same thing. Using localeCompare(), they are.

OK. Thanks again. I will keep that in mind. I definitely need to brush up on string comparisons and decimal math a lot more. Have a tendency to treat everything like an integer and hope someone else already figured out what I was trying to do behind the scenes :grinning:

1 Like

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