Skip to content

Instantly share code, notes, and snippets.

@togakangaroo
Last active August 29, 2015 14:20
Show Gist options
  • Save togakangaroo/2cacfb4e604ac0a7c8ce to your computer and use it in GitHub Desktop.
Save togakangaroo/2cacfb4e604ac0a7c8ce to your computer and use it in GitHub Desktop.
First pass on lecture introducing the concept of arrays

Last week you learned about objects and how objects are used to group data. Of all the things we've taught you so far its probably least clear how you would use these. I assure you, once you get past very simple websites, you use objects all the time. Let's look at some web applications and identify where the objects might be hiding.

http://content.screencast.com/users/togakangaroo/folders/Jing/media/069877db-54cd-40c6-b468-170187d5882e/2015-05-03_0933.png I'll start with the application I just finished writing. We were building it for two years so I can assure you it's not very simple. It's a web application that helps business analysts generate slide decks that answer questions like "why isn't dairy selling in August". Can you tell where some objects probably are? I worked on it so I can tell you. See each of these slid thumbnails below? Each one has a name, a url to the preview image - remember for images you put in a url into the src attribute, you might have difficulty seeing but it also has the name of the last person to make changes to that slide, and the date on which it happened, and also has a number called an Id so that we can say "edit slide 3" or "what happens when we evaluate the data in slide 24"?

I can tell you, what happens here is that the browser actually runs javascript that has these objects that represent slides. We then use javascript to make the html from there. So we say, "ok, the id number goes first, then we create an input and put in there the name, then in a p element we put editor and date/time, then the image"

Alright, enough showing off, let's look at another website I didn't write. I recently used Kayak.com to look up airplane tickets to visit my father in law in New Hampshire http://www.kayak.com/flights/MSY-MHT,LEB,PSM/2015-06-12/2015-06-14/2adults http://content.screencast.com/users/togakangaroo/folders/Jing/media/08a0628b-310a-4f50-86b2-b73545b717c3/2015-05-03_0942.png Where are the objects here?

Ok, we'll do one more. Gmail Here's the pelican's 2014 season roster http://stats.nba.com/team/#!/1610612740/players/?sort=GP&dir=1 http://content.screencast.com/users/togakangaroo/folders/Jing/media/08926ae4-91b9-42ab-a4ac-e7d42b156c80/2015-05-03_0953.png Where are the objects here?

I'm being a bit selective here but are you noticing a trend with when objects are very useful? When there's a bunch of things of the same type. So let's write out what the objecct representing a player might look like

    var anthonyDavis = { };
    anthonyDavis["name"] = "Anthony Davis";
    anthonyDavis["position"] = "Forward-Center";
    anthonyDavis["jerseyNumer"] = 23;
    anthonyDavis["gamesPlayed"] = 68;
    anthonyDavis["winPercentage"] = 0.574;

you might remember seeing it written in a slightly simpler way. For this lesson we're going to avoid this way of writing things out, though you're welcome to use either in the future

    var anthonyDavis = { };
    anthonyDavis.name = "Anthony Davis";
    anthonyDavis.position = "Forward-Center";
    anthonyDavis.jerseyNumer = 23;
    anthonyDavis.gamesPlayed = 68;
    anthonyDavis.winPercentage = 0.574;

You can also write the same thing in a slightly simpler way by using what we call JSON syntax. We will usually be using this as its a bit simpler and less typing.

    var anthonyDavis = {
        "name": "Anthony Davis",
        "position": "Forward-Center",
        "jerseyNumber": 23,
        "gamesPlayed": 68,
        "winPercentage": 0.574,
    };

These are all identical.

Of course we usually want to work with a whole team, not jsut one player. Let's talk through some stuff on the board


So now we need to learn how to translate what we just did to code. Let's start with this - how do you represent the entire pelicans team? Using what we know so far, how would we do that? Well I suppose you could use an object to represent the team and use their jersey number as they key in team

	var pelicans = {};
	pelicans["23"] = anthonyDavis;
	pelicans["1"] = tyrekeEvans;
	pelicans["3"] = omerAsik;

or using JSON syntax

	var pelicans = {
		"23": anthonyDavis,
		"1": tyrekeEvans,
		"3": omerAsik,
	};

of course the jersey number is already in each player's object so thats kind of redundant, if Anthony Davis changes his number to 99 we have to remember to do it in both places. All we need for the key is any unique number

	var pelicans = {
		"1": anthonyDavis,
		"2": tyrekeEvans,
		"3": omerAsik,
	};

Let's say we have only the reference to the pelicans and not to the individual players. What if you wanted to get Tyreke Eavns's win percentage, how would you write that?

pelicans["2"]["winPercentage"];

Why does this work? Well remember, another way to write the above is

	var pelicans = { };
	pelicans["1"] = anthonyDavis;
	pelicans["2"] = tyrekeEvans;
	pelicans["3"] = omerAsik;

That means that we can always do

	var somePlayer = pelicans["2"];
	console.log( somePlayer["winPercentage"] );

What if you needed to find out the number of games Omer Asik has played?

pelicans["3"]["gamesPlayed"] 

Now you get it.

What if you wanted to know the total number of pelicans players on the roster? Well that's possible, but not easy to do with an object. Well fortunately, if we create our pelicans team in a slightly different way it becomes easier. Instead of the above json syntax to create an object, **in order to hold a bunch of objects of the same type we will create an array **

	var pelicans = [
		anthonyDavis,
		tyrekeEvans,
		omerAsik,
	];

Note two differences here. First, we use square instead of mustache brackets, and second, we don't provide keys. That is because an array is going to generate keys for us, just like we did above when we started at 1, 2, 3. The only difference is it will go 0, 1, 2, .... So now, to get the number of games Omer Asik has played we can do

pelicans["2"]["gamesPlayed"]

Since we know that Anthony Davis is first in the array, we can use the "0" key to get his jersey number

Pelicans["0"]["jerseyNumber"]

And to get the number of pelicans we can simply do

pelicans.length	

That's interesting. So if we wanted to get the name of the last person on the roster we can do

	var lastKey = pelicans.length - 1;
	var lastPerson = pelicans[lastKey];
	var lastPersonName = lastPerson["name"];

Why does this work?

Note that once we're comfortable with this concept, we could also write it all out in one step

pelicans[ pelicans.length - 1 ]["name"]

But length isn't the only thing that's nice about arrays. There's a couple other really neat things they can do.

What if you wanted to get the name of every player on the team?

Let's say we have a variable named player how do you get the name?

var name = player["name"];

Ok, now how would we create a function called getPlayerName that takes a player and returns the name?

	var getPlayerName = function(player) {
		return player["name"];
	};

Great, now that we have this we can get all the player names. In javascript, in addition to length every array has another property called map. This property is a function that you call. map takes a single parameter which is another function that runs on every item in the array to return a new array. It's easier just to show you.

	var allPlayerNames = pelicans.map( getPlayerName );
	console.log(allPlayerNames);

So what happened here? The map function ran getPlayerName on every pelican player object, since the function returned the name for each player the whole thing then returns an array of strings.

If you prefer we could write this all in one step too

	pelicans.map( function(player) {
		return player["name"];
	});

How would you get all jersey numbers?

How would you get a list of all jersey numbers and names? Something like

"23 - Anthony Davis"
"1 - Tyreke Evans"
"3 - Omer Asik"

Hint: start by writing a getPlayerNumberAndName function that takes a player and returns the string "(player jerseyNumber) - (player name)".

This is insanely useful, we can now get names, numbers, and any information for the people on the team. We could do calculations and take each player's number of points scored and divide by number of games to get number of points per game. This is important! When people pay developers to build real applications it's rarely just because they want to make things pretty, its usually because they have data and want easier/faster ways of understanding and working with it.

There is still a few type of questions that we would have trouble answering with just map. For example, who are the players who have played over 40 games this season? Can we use map here?

Well, since map runs once on each item, and makes a new array from what the function returns, it will always have the same amount of items coming out as going in. But there will presumably be fewer players who have played over 40 games than the entire roster, so maybe map is not correct?

To help with the question where you expect fewer items from the array we have another function called filter. To use filter let's write another function. This one will be named isAFrequentPlayer and will again take a single player parameter and answer the question "has this player played over 40 games?

So given a variable player what sort of if test could you do to determine whether this player has played over 40 games?

	if( player["gamesPlayed"] > 40 ) {
		console.log(player["name"] + " has played over 40 games!");
	} else {
		console.log(player["name"] + " has NOT played over 40 games");
	}

So let's put that in a function that returns true (the player has played over 40 games) or false (the player has not)

	var isAFrequentPlayer = function(player) {
		var result;
		if( player["gamesPlayed"] > 40 ) {
			result = true;
		} else {
			result = false;
		}
		return result;
	}

now we can use this

	var allFrequentPlayers = pelicans.filter(isAFrequentPlayer);

What sort of thing would be in allFrequentPlayers? It will be yet another array of player objects, but ONLY the ones for which the test above returned true.

We could combine these things! For example, let's say we wanted to get the names of all frequent players.

	var frequentPlayerNames = pelicans.filter( isAFrequentPlayer ).map( getPlayerName );

Aside:

It can all be a bit easier in fact. Consider that 10 > 40 will give you false and 50 > 40 gives you true (try it out in the console). Therefore player["gamesPlayed"] > 40 will give you true when the player has played over 40 games and false otherwise. In light of that, our current implementation of isAFrequentPlayer should seem a bit redundant. In fact it is, it can be easily shortented to

	var isAFrequentPlayer = function(player) {
		return player["gamesPlayed"] > 40;
	};

feel free to play around with both approaches until you're comfortable with it. The big benefit, is, because both of these functions are so simple you can often write everything out all at once

	var allFrequentPlayerNames = pelicans.filter( function(filterPlayer) {
									return filterPlayer["gamesPlayed"] > 40;
								} ).map( function(mapPlayer) {
									return mapPlayer["name"];
								} );

Again, feel free to experiment with the approach that suits you (and your code) best.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment