|
function inventory(arr1, arr2) { |
|
var addItems = []; |
|
var existingItems = []; |
|
var i,j; |
|
// update existing items and detect existing items |
|
for (i=0;i<arr1.length;i++){ |
|
for (j=0;j<arr2.length;j++){ |
|
if (arr1[i][1] == arr2[j][1]){ |
|
arr1[i][0] = arr1[i][0] + arr2[j][0]; |
|
existingItems.push(arr2[j][1]); |
|
} |
|
} |
|
} |
|
// detect new items to be added to inventory |
|
for (j=0;j<arr2.length;j++){ |
|
if (existingItems.indexOf(arr2[j][1]) == -1){addItems.push(arr2[j]);} |
|
} |
|
// push new items to inventory |
|
for (j=0;j<addItems.length;j++){arr1.push(addItems[j]);} |
|
// sort final arr1 |
|
arr1.sort(function(a,b){ |
|
if(a[1] < b[1]) return -1; |
|
if(a[1] > b[1]) return 1; |
|
return 0; |
|
}); |
|
return arr1; |
|
//return addItems; |
|
//return arr1InsertIndex; |
|
//return JSON.stringify(addItems); |
|
} |
|
//inventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]); |
|
//inventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"], [6, "Zoom"]]); |
|
inventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]); |