Wednesday, April 11, 2018

Sorting Objects in arrays

I finished a challenge on Free Code Camp called Inventory Update. The challenge asked you to update the first array (inventory) with either the array 2 (delivery) items if they don't exist in the inventory or update the inventory number if the item already exists in the inventory.

The arrays weren't objects with names, they came across with an integer and text. For example, my first item in array one was [10, "Bowling Ball"]. I probably could have converted each item in the array to an inventory item so then I would have [quantity: 10, name: "Bowling Ball"]. But with the all you can do with arrays I didn't find that necessary (although if this were a program for someone, it would have been beneficial to make the array into a more usable format instead of using array1[i][0].

Adding new items and updating the value of an item already in inventory seemed easy. I created a function to see if the array contained the inventory item and updated the amount. If it didn't contain it, push in the new array item.

function contains(obj) {
for (var i = 0; i < arr1.length; i++) {
if (arr1[i][1] === obj[1]) {
arr1[i][0] += obj[0];
return true;
}
}
arr1.push(obj);
return false;
}

Now came the more tricky part. The challenge asked you to alphabetize the items in the inventory. You know, make it easy to find an item in the list. I tried arr1.sort() but this seemed to just sort off the first item in the object of the array which was the quantity in the inventory. Great if I know the quantity of whatever I was looking up, but doesn't really make sense.

While reading, I found that you can create a function to sort your items in the array. This allows you to write a function to alphabetize based on the second member of my object, or the name of my inventory item.

I looked further and found a better way that didn't require me to write a function. Using String.prototype.localeCompare(). This compares the strings you have and returns a number that indicates whether the reference string comes before, after, or is the same as the other string provided. It then will sort the items for you.

This will allow for some options as well, such as case sensitivity, numeric, ignoring punctuation and more. It made the sorting pretty easy and able to use one line of code:

arr1.sort((a, b) => a[1].localeCompare(b[1]));

(if I had made each item in the array into an inventory object it would have been a.name and b.name instead of a[1] and b[1]).

I could see localeCompare coming in handy later in life.
"I have noticed that nothing I never said ever did me any harm." - Calvin Coolidge

No comments: