【FCC】Inventory Update

题目:

依照一个存着新进货物的二维数组,更新存着现有库存(在 arr1 中)的二维数组. 如果货物已存在则更新数量 . 如果没有对应货物则把其加入到数组中,更新最新的数量. 返回当前的库存数组,且按货物名称的字母顺序排列.

示例:

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的数组.
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”]].
updateInventory([[21, “Bowling Ball”], [2, “Dirty Sock”], [1, “Hair Pin”], [5, “Microphone”]], []) 应该返回 [[21, “Bowling Ball”], [2, “Dirty Sock”], [1, “Hair Pin”], [5, “Microphone”]].
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”]].
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”]].

分析思路:

遍历进货数组,取每一个元素,然后遍历库存数组,若进货的名称已存在,直接修改数目,若进货的名称不存在,这 push 到库存中;
从测试用例中可知:最终的库存列表需要根据名称进行排序,从字符的低到高进行排序;

代码:

<script type="text/javascript">
	function updateInventory(arr1, arr2) {
		// All inventory must be accounted for or you're fired!
		for (var i = 0; i < arr2.length; i++) {
			for (var j = 0; j < arr1.length; j++) {
				if (arr1[j][1] === arr2[i][1]) {
					arr1[j][0] += arr2[i][0];
					break;
				}
			}

			if (j == arr1.length) {
				arr1.push(arr2[i]);
			}
		}

		return arr1.sort(function(a, b) {
			return a[1].charCodeAt(0) - b[1].charCodeAt(0);
		});

	}
</script>

 

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注