DEV Community

Cover image for Navigate Arrays like you're Talking to a 4-year-old
Barbara Law
Barbara Law

Posted on • Edited on

Navigate Arrays like you're Talking to a 4-year-old

Are you an experienced coder? Are you well-versed in data types and their manipulation? If you answered 'yes' to either of those questions that's awesome and I'd love to talk code with you sometime! However this post will likely not enlighten you at all.

But if you're a newbie struggling to wrap your head around some intimidating looking syntax (something like myArray[2][0][myArray[2][0].length-1] perhaps?), I may be able to help you a little bit.

This article assumes you know the basic structure of a JavaScript array and have been introduced to bracket notation but are in the process of trying to actually use that to access the data within. My advice? Pretend your computer is a 4-year-old who needs to find their favorite socks.

Let me Explain

If you've ever spent a fair amount of time with a preschooler then you've likely experienced their unique way of interpreting 'simple' instructions. If you haven't then please just trust me when I tell you that instructions to a preschooler have to be explicit - both thorough and unambiguous - or results may vary. Computers interpret instructions in much the same way.

All you want are the socks

Imagine a small heap of a kid's clothes, it would be a pretty simple matter to just grab the socks. Look at array kidStuff, how could you access just 'favorite socks'?

let kidStuff = ['red shirt', 'favorite socks', 'cool shorts']
Enter fullscreen mode Exit fullscreen mode

The array is 1-dimensional, it contains only strings, no complex data types. You can use bracket notation and the index of 'favorite socks' to access them, like so: array name[index number].

Which index do we want to use in this case? Remember, we begin counting from index 0 in JavaScript.

alert(`Here are your ` + kidStuff[1])    
// 'Here are your favorite socks'
Enter fullscreen mode Exit fullscreen mode

Now what if our socks were put away in a chest of drawers? What if our array looked like this?

let kidDresser = [
  [['red pj top', 'red pj bottom', 'cars pj top', 'cars pj bottom'],['plaid pj top', 'plaid pj bottom', 'long sleeve pj top', 'long sleeve pj bottom'],['shark swim shirt', 'shark swim shorts']],
  [['grey sweatpants', 'black sweatpants', 'jeans', 'red joggers'],['orange hoodie', 'green sweater']],
  [['karate tshirt', 'karate pants'], ['blue shorts', 'grey shorts', 'navy shorts'], ['white socks', 'striped socks', 'favorite socks', 'holiday socks']]
]
Enter fullscreen mode Exit fullscreen mode

How is our computer kid to find their favorite socks? Your job is to tell them exactly where they are. Take a deep breath, if you can tell a kid where in their dresser those socks are, you can code it.

Where are they?

In plain talk, where are the socks? Go ahead and take a look at the same array again, this time with some comments and spacing thrown in.

let kidDresser = [

  // Top Drawer
  [
    ['red pj top', 'red pj bottom', 'cars pj top', 'cars pj bottom'],
    ['plaid pj top', 'plaid pj bottom', 'long sleeve pj top', 'long sleeve pj bottom'],
    ['shark swim shirt', 'shark swim shorts']],

  // Middle Drawer
  [
    ['grey sweatpants', 'black sweatpants', 'jeans', 'red joggers'],
    ['orange hoodie', 'green sweater']],

  // Bottom Drawer
  [
    ['white socks', 'striped socks',  'holiday socks', 'favorite socks'],
    ['karate tshirt', 'karate pants'], 
    ['blue shorts', 'grey shorts', 'navy shorts']]
]
Enter fullscreen mode Exit fullscreen mode

Nothing meaningful was changed about the array this time, only spacing and comments. Try to describe where the 'favorite socks' can be found, in regular speech (not code).

How did you describe their location? Moving from the outside in, I would say they are in the kid's dresser drawers, bottom drawer, first section, last pair in.
If this isn't similar to your answer please review the code above and see if you can find the socks via those instructions.

In JavaScript

Now that we know where the socks are in plain speech, we will locate them using JavaScript array bracket notation.

We know the socks are in the dresser, so we'll start there:

Dresser with 3 drawers

In Javascript,

alert(`Here are your ` + kidDresser)
// Alerts contents of entire dresser! Oops
Enter fullscreen mode Exit fullscreen mode

Our preschooler computer doesn't have the presence of mind to just go from being told the socks are in the dresser to actually having the socks - we need to drill down to exactly where they are.

Bottom drawer of Dresser

The socks were in the bottom drawer, which in this case was the 3rd 'drawer', or kidDresser[2] when remembering to start counting from index 0.

In Javascript,

alert(`Here are your ` + kidDresser[2])
// Alerts contents of whole bottom drawer! Yikes
Enter fullscreen mode Exit fullscreen mode

We're getting closer. Next we need to point to the first section of that drawer.

Sections inside bottom drawer

Keep in mind, 'first' translates to index 0 when discussing JavaScript arrays. How do we describe this [0]th element in our code? Here's one way:

let sockDrawer = kidDresser[2]   // Bottom drawer from above
let sockSection = sockDrawer[0]  // First section of drawer
Enter fullscreen mode Exit fullscreen mode

Alternatively, you can code that section as follows:

let sockSection = kidDresser[2][0]
Enter fullscreen mode Exit fullscreen mode

Now we are directing the preschooler code to the correct section of the correct drawer in the dresser, but we still need to be more specific to find our favorite socks.

alert(`Here are your ` + kidDresser[2][0])
// Alerts contents of whole sock section! Messy
Enter fullscreen mode Exit fullscreen mode

We know 'favorite socks' are the last pair of socks in their section. In this case there are 4 pairs of socks total, making our favorites the pair at index [3].

Socks within bottom drawer section

Similarly to selecting the section of the drawer, we can tack on the sock pair's index to our code to select them:

alert(`Here are your ` + kidDresser[2][0][3])
// Alerts `Here are your favorite socks` 
// Victory is ours!
Enter fullscreen mode Exit fullscreen mode

We did it! Our computer preschooler has their favorite socks and all is right with the world!

Those are the basics of directing a 4-year-old!

Treating the computer like a preschooler helps me, and I hope it helps you! I hope this walkthrough helped you get a grasp of basics of array navigation in JavaScript.


But what if...

What if we didn't know how many socks were in that first section of the bottom drawer? What if we only knew the favorite socks were the last pair?

Given the sock section, in Javascript:

let sockSection = kidDresser[2][0]
Enter fullscreen mode Exit fullscreen mode

How can we select its last item, no matter how many items that section holds?

We can use the 'length' property.

An array's length is equal to the number of elements in that array. We already know that we refer to an element by their index, which begin at 0. Therefore the last element in an array will have an index of length-1.

Here's an example to help visualize:

let sockSection = ['white socks', 'striped socks',  'holiday socks', 'favorite socks']

console.log(sockSection.length)                  // 4
console.log(sockSection[4-1])                    // 'favorite socks'
console.log(sockSection[sockSection.length - 1]) // 'favorite socks'
Enter fullscreen mode Exit fullscreen mode

Now no matter how many socks we cram in the sock section in front of our favorite socks, we can always grab just our favorites. Take time with that concept and let it sink in a bit.

The Intimidating Code

Here's the scary piece of code I included in the introduction of this post

myArray[2][0][myArray[2][0].length-1]
Enter fullscreen mode Exit fullscreen mode

It's messy, it's intimidating, and frankly I wouldn't write it like this - but let's break it down right now, understand it, and own it.
If we replace 'myArray' with 'kidDresser' in that code, it points to our 'favorite socks'.

Let's break that code into pieces:

let scaryStuff = kidDresser[2][0][kidDresser[2][0].length-1]
alert(`Here are your ` + scaryStuff)
// Alerts `Here are your favorite socks`.

let bottomDrawer = kidDresser[2]

let sockSection = bottomDrawer[0] 
// equivalent to kidDresser[2][0]

let lastSock = sockSection[sockSection.length-1]
//equivalent to kidDresser[2][0][kidDresser[2][0].length-1]

alert(`Here are your ` + lastSock)
// Alerts `Here are your favorite socks`.
Enter fullscreen mode Exit fullscreen mode

Look at that! We destroyed that mess of a line of code and made it readable.

Top comments (2)

Collapse
 
parejaonpurpose profile image
ParejaOnPurpose

This was exceptionally helpful. I'm a newbie in class and a JS bootcamp. This best example I've been given on this subject. Thanks so much. I once was blind but now I see. Looking forward to more of your posts.

Collapse
 
barbaralaw profile image
Barbara Law

I'm glad you liked it! Thanks for checking it out :)