Going on an Array Hunt in JavaScript
A chocolate focused guide to getting what you want out of an array
I’m not scared!
Arrays are everywhere. Think about being in the grocery store and walking down the aisle. Might look something like this:
At the core, an array is a collection of similar elements stored together in an adjoining neighborly way. Picture a new sub-development with the lots all neatly divided…also an array. Egg carts, post-office boxes, medication pill packs are set up in arrays.
Arrays are a frequently used data structure in programming for multiple reasons including speed (iterations are fast), easier debugging, and reusability of the code. They aren’t without their downsides especially if the array is going to be very large, but that’s a completely different discussion.
I have an array…now what?
Arrays in JavaScript are objects, but they also have some additional methods (actions) that can be performed to manipulate the data inside. Arrays in JavaScript are zero-indexed which means that the element in the first box (slot, location, etc) is 0
. This also means that the length of the array will be 1 less than you expect.
Example
If we put 10 candies in the array, the first one is at index 0
and the last one is at index 9
.
Here’s the array we are going to learn with today…we’ll call it candies
Each element(candy) of our candies array has the color stored as it’s value:
Figuring out which method (action) to use depends on what you actually want to do with items (or elements or candies or whatever you want to call them) inside the array.
Basic Syntax: array.method(element=>action on the element)
Here’s our breakdown:
array
is the name of the array we are working with.method
is the specific action we want to use on the array itself
Now we are going inside the parentheses. In here we look at each individual element to perform an action, do a comparison, etc on it.
element
is the individual element at this spot in the array, we can name it anything we want as long as we are consistent.action on the element
is some specific thing we are going to do. We can look at properties of the item, check for true/false values, or a variety of other things.
Let’s get into some real examples.
.find()
We want a quick snack and decide we want to find the first blue M&M we can grab. Array.find() allows us to grab the first item with the matching property in our candies array.
Example syntax: candies.find(candy => candy==='blue')
Go through candies array candy by candy to find the first one that is blue.
.filter()
Now we want to collect all the ones that are red M&Ms into a different group because we want to eat them last.
Example syntax: candies.filter(candy=>candy==='red')
This returns a NEW array without changing the original one.
let allReds = candies.filter(candy=>candy==='red')
allReds
Array(3) [ "red", "red", "red" ]
candies
Array(10) [ "green", "red", "orange", "blue", "blue", "brown", "red", "yellow", "orange", "red" ]
.map()
What if we want to do something to each and every element in our array? We could square each number or multiply it by 4. For our candies, we want to get the first letter of each element’s (candy) color. We are mapping a COPY of our original array to be changed however we want.
Example syntax: candies.map(candy=>candy.charAt(0))
let firstLetterOfCandy = candies.map(candy=>candy.charAt(0))
firstLetterOfCandy
Array(10) [ "g", "r", "o", "b", "b", "b", "r", "y", "o", "r" ]
candies
Array(10) [ "green", "red", "orange", "blue", "blue", "brown", "red", "yellow", "orange", "red" ]
And again, like filter() we have no changes to our original array.
.reduce()
Now we get to reduce. Early on it seems to be taught as it’s name says…reducing the array to a single value, especially when trying to sum up totals. This one has a slightly different syntax because there is a value used to keep track of the iterations which you will often see written as accumulator
.
Example would be an array like this [2,4,6,8,10]
named numbers
.
Basic syntax: array.reduce(function(accumulator,currentValue, currentIndex,array), initialValue)
The entire first argument is a function that can take 4 arguments.
accumulator
keeps track of results of your function.currentValue
is the value of the current element on this iteration.currentIndex
is current location in the array ofcurrentValue
. optionalarray
is the original array element. optional
Example syntax: numbers.reduce((sum, currentValue)=>sum + currentValue, 0)
let numbers = [2,4,6,8,10]
numbers.reduce((sum, currentValue)=>sum + currentValue, 0)
30
Where reduce can get really handy is that it’s capable of transforming the array and returning more than just a simple number. Here’s another example using our candies array. I made the array larger so that we have the whole bagOfCandy
. I want to know how many of each color are in that bag. Reduce can do this for us even with non-numeric elements!
candies.length //added more candy
// 191
let bagOfCandy = candies.reduce((countByColor, candy) => {
countByColor[candy] ? (countByColor[candy] += 1) :
(countByColor[candy] = 1);
return countByColor;
}, {});
//bagOfCandy {"green": 11,"red": 60,"orange": 40,
// "blue": 40,"brown": 20,"yellow": 20}
Here’s what all this means. countByColor
is our accumulator and if you look at the end of the reduce function, I’ve given it an empty object {}
as it’s initial value. Now it starts going through candies
one by one and for each candy
and looking at its value which for us is the color. So the first candy
is green. If there is no green key in the countByColor
it will create one and give it the number 1. Now it goes through again, finds a red candy
, checks to see if there is a key for red in countByColor
and there is not, so the red key is created and is set to the number 1. The third candy
is also red. We check to see if it exists in countByColor
and it does! We can now increase the number by 1 since that is the second red we have seen. It will continue this way until there is no more candy
in candies
. The return is the object countByColor
which gives the output as shown on the screen.
We just reduced a bag of M&Ms to tell us how many of each color were in there. Reduce is so much more powerful than it’s initially taught and has a lot of useful applications when used correctly.
Arrays are everywhere but they are not something to be scared of. They can be used in many ways to speed up calculations, processing, and storage of information. Just don’t forget which index you’re supposed to be working out of.