You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript splice方法索引混乱导致freeCodeCamp库存更新算法结果错误

freeCodeCamp Inventory Update 问题解法错误排查

你的代码存在三个核心问题

  • 第一个错误:遍历重复索引时用了for...in遍历duplicates数组,拿到的index是duplicates自身的索引,而非你存储的待删除的newInv索引。比如你的示例中duplicates存储的是[4,2](对应新到货的Hair Pin和Bowling Ball在newInv里的索引),但for...in拿到的是0和1,导致你删的是newInv的第0项和第1项,刚好把原有库存的Bowling Ball和Dirty Sock删掉了,自然只剩下新到货的重复项。
  • 第二个错误:你没有按照题目要求合并重复商品的库存数量,只是简单删除其中一条记录,正确逻辑应该是原有库存数量 + 新到货数量,而非二选一保留。
  • 第三个错误:就算你拿到了正确的待删除索引,用splice从前到后删除也会导致后续索引偏移,比如先删索引2的元素,原索引4的元素会变成索引3,再删4就会删错。

更简洁的正确实现思路

用对象做中间映射存储商品和对应数量,避免处理复杂的索引匹配问题:

function updateInventory(arr1, arr2) {
    // 把现有库存转成对象,键为商品名,值为库存数
    const inventoryMap = Object.fromEntries(arr1.map(([count, name]) => [name, count]))
    // 遍历新到货更新库存
    for (const [addCount, name] of arr2) {
        inventoryMap[name] = (inventoryMap[name] || 0) + addCount
    }
    // 转成二维数组后按商品名字母排序
    return Object.entries(inventoryMap)
        .map(([name, count]) => [count, name])
        .sort((a, b) => a[1].localeCompare(b[1]))
}

原有逻辑的修正版

如果你想要基于你写的逻辑修改,可参考如下代码:

function updateInventory(arr1, arr2) {
    let newInv = [...arr1, ...arr2]
    let temp = newInv.flat().filter(item => typeof item === 'string')
    let duplicates = temp.reduce((acc, item, index) => {
        if (temp.indexOf(item) != index){
            // 先累加重复商品的数量到第一条记录上
            newInv[temp.indexOf(item)][0] += newInv[index][0]
            acc.push(index)
        }
        return acc
    }, [])
    // 从后往前删,避免索引偏移
    duplicates.sort((a,b) => b - a).forEach(idx => {
        newInv.splice(idx, 1)
    })
    newInv.sort((a,b) => a[1].localeCompare(b[1]))
    return newInv
}

内容的提问来源于stack exchange,提问作者Rori

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 17:15:03