我试图添加匹配数组的所有数字并删除重复的名称。它适用于第一个实例,但while循环不会超过Apples。
function updateInventory(arr1, arr2) {
function alphabetizer(a, b) {
if (a[1] < b[1]) return -1;
if (a[1] > b[1]) return 1;
return 0;
}
var newInv = arr1.concat(arr2).sort(alphabetizer);
for(var i = 0; i < newInv.length; i++) {
while(newInv[i][1] === newInv[i++][1]) {
newInv[i] += newInv[i++][0];
newInv.push([newInv[i][0], newInv[i][1]]);
newInv.splice(i,2);
}
}
return newInv;
}
// Example inventory lists
var curInv = [
[21, "Bowling Ball"],
[2, "Dirty Sock"],
[1, "Hair Pin"],
[5, "Microphone"],
[10, "Apples"]
];
var newInv = [
[9, "Apples"],
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];
updateInventory(curInv, newInv);
它一直给我错误TypeError: newInv[(+ i)] is undefined
但是我不确定为什么因为我被定义了,如果我只是尝试运行newInv[i]
我得到了第一个结果。
答案 0 :(得分:1)
有几个地方需要修复。我更新了这个jsfiddle
function updateInventory(arr1, arr2) {
function alphabetizer(a, b) {
if (a[1] < b[1]) return -1;
if (a[1] > b[1]) return 1;
return 0;
}
var newInv = arr1.concat(arr2).sort(alphabetizer);
for (var i = 0; i < newInv.length; i++) {
var j = i;
while (newInv[j + 1] && newInv[j][1] == newInv[j + 1][1]) {
newInv[j][0] += newInv[j + 1][0];
newInv.splice(j + 1, 1);
j++;
}
}
document.getElementById('test').innerHTML = newInv.join('<br>');
}
// Example inventory lists
var curInv = [
[21, "Bowling Ball"],
[2, "Dirty Sock"],
[1, "Hair Pin"],
[5, "Microphone"],
[10, "Apples"]
];
var newInv = [
[9, "Apples"],
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];
updateInventory(curInv, newInv);