正文
FCC(ES6写法) Inventory Update
小程序:扫一扫查出行
【扫一扫了解最新限行尾号】
复制小程序
【扫一扫了解最新限行尾号】
复制小程序
依照一个存着新进货物的二维数组,更新存着现有库存(在
arr1
中)的二维数组. 如果货物已存在则更新数量 . 如果没有对应货物则把其加入到数组中,更新最新的数量. 返回当前的库存数组,且按货物名称的字母顺序排列。
思路:
1.先写个函数,功能是判断该数组是否存在该字符串,存在则返回一个index。
2.循环遍历第二个数组,如果在第一个数组中存在当前货物名,则把数量相加,如果不存在就push进去。最后别忘了排序,这里可以用charCodeAt来计算,也可以用三目来比大小,如:a[1][0] > b[1][0] ? 1: 0 ;
let updateInventory = (arr1, arr2) => { arr2.forEach( v => { let i = hasValue(v[1],arr1); i === undefined ? arr1.push(v) : arr1[i][0] += v[0]; }); return arr1.sort((a,b) => a[1].charCodeAt(0) - b[1].charCodeAt(0)); }; let hasValue = (str,arr) => { for(let i in arr){ if(arr[i][1] === str) return i; } }; updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]);
如果有不明白的地方请留言,如果有更好更简便更优化的方法请留言,谢谢。
更多内容请访问我的个人博客:Bblog