Sitemap

JavaScript Algorithms: Inventory Update

4 min readNov 23, 2018

--

Continuing my conquest of the FreeCodeCamp algorithms series… my latest problem: updating a 2D array with data from another 2D array.

What is a 2D array?

A two dimensional array (also known as a matrix) is an array of arrays. Each of the inner arrays contain the same number of elements. Each index of the inner array corresponds to a name much like each column in a table corresponds to a name. Still confused? Good. Here’s a diagram:

Press enter or click to view image in full size
Inventory in table form

Chances are you have no problem understanding the table above. Tables arrange things in rows and columns. The column header names everything in the corresponding column. Each row represents a single item and contain attributes describing that item. Those attributes are arranged into the column that corresponds to their name. You’ll notice that columns always contain the same type of element. For example, “Quantity” contains only numbers and “Item” contains only strings. This is an important constraint in 2D arrays and, in fact, it is a requirement.

Here’s what this would look like as a 2D array:

const curInv = [
[21, 'Bowling Ball'],
[2, 'Dirty Sock'],
[1, 'Hair Pin'],
[5, 'Microphone']
];

Not that much different than a table, right? However, you’ll notice there isn’t anything telling you what each “column” means. It’s assumed you already know what each “column” means and your code is configured elsewhere to deal with it.

A few other things to notice:

  1. Each item in the outer array must be an array.
  2. Each inner array must contain the same number of items.
  3. The index of each inner array (column) must be the of the same type.

Putting it all together

Get Tim Nelson’s stories in your inbox

Join Medium for free to get updates from this writer.

So to break it down, here are the procedures that must happen:

  1. Validate the two 2D arrays based on the above criteria.
  2. Loop through the array containing the new data and determine whether each item exists in the inventory array.
  3. If it does, update the quantity column.
  4. If it doesn’t, create a new array and add it to the inventory array.
  5. Sort the array alphabetically.

Solution

If you use this data…

const curInv = [
[21, 'Bowling Ball'],
[2, 'Dirty Sock'],
[1, 'Hair Pin'],
[5, 'Microphone']
];
const newInv = [
[2, 'Hair Pin'],
[3, 'Half-Eaten Apple'],
[67, 'Bowling Ball'],
[7, 'Toothpaste']
];

and run it though the update function…

updateInventory(curInv, newInv)

the result should be…

[ 
[ 88, 'Bowling Ball' ],
[ 2, 'Dirty Sock' ],
[ 3, 'Hair Pin' ],
[ 3, 'Half-Eaten Apple' ],
[ 5, 'Microphone' ],
[ 7, 'Toothpaste' ]
]

Let’s talk more about objects

updateInventory doesn’t even need to return anything if you pass a predefined array as the first parameter. Why? Arrays are object and objects behave differently than value types when you pass them to functions. When you pass a value type (number or string), it copies that value. When you pass an object, it copies the memory address to that object but the object itself does not get copied. For example:

let mynum = 1;
const fun = (num) => {num += 1;};
fun(mynum);
console.log(mynum) //returns `1`

As you can see above, mynum is not affected when it gets passed into fun() because mynum is a value type. However if you were dealing with objects, it would be a different story:

const arr = ['hello'];
const updateArray = (o) => {o[0] += ' world';};
updateArray(arr)
console.log(arr[0]) // returns `'hello world'`

Since arr is an object, we’re coping the memory address to the arr when we pass it to the updateArray(). The object itself does not get copied so updateArray() ends up updating the original object and not simply a copy of the object.

So to bring this home, in updateInventory() we could omit return arr1; and curInv would still be updated. More importantly, if you did assign the result of updateInventory() to a new variable, you might be tempted to think it’s somehow different than curInv when in fact it is not. The new variable would point to the same spot in memory as curInv and you might end up confusing yourself if you expected to keep curInv untouched.

If you really wanted that to preserve curInv, I suggest you make a copy of it before you run it through updateInventory(). There are a number of ways you can do that but the quick and dirty way to do is is to convert it to a string then convert it back to an object:

const CLONE = (obj) => {
return JSON.parse(JSON.stringify(obj));
};
const clonedCurInv = CLONE(curInv);

There are more eloquent (and probably more efficient) ways to do it but I’ve found that this works well in most cases.

--

--