FCC题目:依照一个存着新进货物的二维数组,更新存着现有库存(在 arr1
中)的二维数组. 如果货物已存在则更新数量 . 如果没有对应货物则把其加入到数组中,更新最新的数量. 返回当前的库存数组,且按货物名称的字母顺序排列。
结果:
1 updateInventory() 应该返回一个数组. 2 updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]).length 应该返回一个长度为6的数组. 3 updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]) 应该返回 [[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [3, "Half-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]]. 4 updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], []) 应该返回 [[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]]. 5 updateInventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]) 应该返回 [[67, "Bowling Ball"], [2, "Hair Pin"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]]. 6 updateInventory([[0, "Bowling Ball"], [0, "Dirty Sock"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]]) 应该返回 [[1, "Bowling Ball"], [0, "Dirty Sock"], [1, "Hair Pin"], [1, "Half-Eaten Apple"], [0, "Microphone"], [1, "Toothpaste"]].
代码:
1 function updateInventory(arr1, arr2) { 2 // All inventory must be accounted for or you're fired! 3 console.log("ddd"); 4 arr2.forEach(function(vl,ix){ 5 var index=isExit(vl[1],arr1); 6 if(index!==undefined){ 7 arr1[index][0]=arr1[index][0]+vl[0]; 8 }else{ 9 arr1.push(vl); 10 } 11 }); 12 //检查str是否在arr中存在,如果存在,返回下标 13 function isExit(str,arr){ 14 for(var i=0;i<arr.length;i++) 15 if(arr[i][1]==str) return i; 16 } 17 return arr1.sort(function(a,b){ 18 return (a[1][0]>b[1][0])? 1 : 0; 19 }); 20 } 21 22 // Example inventory lists 23 var curInv = [ 24 [21, "Bowling Ball"], 25 [2, "Dirty Sock"], 26 [1, "Hair Pin"], 27 [5, "Microphone"] 28 ]; 29 30 var newInv = [ 31 [2, "Hair Pin"], 32 [3, "Half-Eaten Apple"], 33 [67, "Bowling Ball"], 34 [7, "Toothpaste"] 35 ]; 36 37 updateInventory(curInv, newInv);