main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
 * Inventory Update
 * https://www.freecodecamp.org/challenges/inventory-update
 * Compare and update 2D inventory array against a provided input
 *
 * Ashen Gunaratne
 * [email protected]
 *
 */

function updateInventory(arr1, arr2) {
  // All inventory must be accounted for or you're fired!

  const inventory = Array.prototype.concat.apply([], arr1);
  
  for (let i = 0; i < arr2.length; i++) {

    // extract item properties for easy reference
    const item = arr2[i][1];
    const quantity = arr2[i][0];

    // check if item already exsists in inventory
    const position = inventory.indexOf(item);

    // exsisting item: update quantity
    if (position !== -1) {
      const row = Math.floor(position / 2);
      arr1[row][0] += quantity;
      continue;
    }

    // alien item: add to inventory
    arr1.push([quantity, item]);

    }

  // sort inventory in alphabetical order
  arr1.sort((previous, next) => (previous[1] > [next[1]]) ? 1 : -1);

  return arr1;
}

// test here
// Example inventory lists
var curInv = [
  [21, "Bowling Ball"],
  [2, "Dirty Sock"],
  [1, "Hair Pin"],
  [5, "Microphone"]
];

var newInv = [
  [2, "Hair Pin"],
  [3, "Half-Eaten Apple"],
  [67, "Bowling Ball"],
  [7, "Toothpaste"]
];

updateInventory(curInv, newInv);
Native Browser JavaScript