【发布时间】:2021-12-23 08:21:27
【问题描述】:
我知道这听起来很有趣,因为我自己编写了解决方案,但是在一段时间没有看到它之后,我很难理解为什么它会起作用。该算法解决了 freecodecamp 的“库存更新”问题,尽管测试失败(比较并更新存储在 2D 数组中的库存与新交付的第二个 2D 数组。更新当前现有的库存项目数量(在 arr1 中)。如果找不到商品,则将新的商品和数量添加到库存数组中。返回的库存数组应按商品的字母顺序排列。)算法如下:
function updateInventory(arr1, arr2) {
let newInv = [...arr1, ...arr2]
//create single list of items only from both arrays
let temp = newInv.flat().filter(item => typeof item === 'string')
//create list of the index of all duplicate items
let duplicates = temp.reduce((acc, item, index) => {
if (temp.indexOf(item) != index){
acc.push(index)
}
return acc
}, [])
//remove duplicate items
for (let index in duplicates) {
newInv.splice(index, 1)
}
//sort by alphabetical order
newInv.sort((a,b) => {
return a[1] > b[1] ? 1 : -1
})
return newInv
}
// 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"]
];
updateInventory(curInv, newInv);
据我了解,预期结果应该是:
[ [ 21, 'Bowling Ball' ],
[ 2, 'Dirty Sock' ],
[ 1, 'Hair Pin' ],
[ 3, 'Half-Eaten Apple' ],
[ 5, 'Microphone' ],
[ 7, 'Toothpaste' ] ]
然而,得到的是:
[ [ 67, 'Bowling Ball' ],
[ 2, 'Dirty Sock' ],
[ 2, 'Hair Pin' ],
[ 3, 'Half-Eaten Apple' ],
[ 5, 'Microphone' ],
[ 7, 'Toothpaste' ] ]
这是要删除的元素的重复对。我确定我可能遗漏了一些简单的东西,但我就是不明白。
非常感谢您的帮助
【问题讨论】:
-
我认为您不会收到我对答案所做的编辑的通知...并且由于您已经将其标记为已解决,我只想以这种方式提及,我只是添加了另一种解决方法我认为可能感兴趣的任务
标签: javascript indexing splice