Chapter 7
Data Structures

Only the simplest programs can get away with storing data in variables. But these next programs will get you to think about storing data in lists or name/value pairs, or even a combination of the two.

Depending on the language you choose, you might be looking for arrays, lists, hashes, hashmaps, dictionaries, associative arrays, or maps. And while languages have different names, the concepts are the same. You group data together using data structures. To keep it simple, I’m going to use the terms array and map.

An array is a data structure that holds a list of values:

 
colors = [​"Red"​, ​"Green"​, ​"Blue"​];

Usually, the order of items in the array is preserved. To get a value out, you access it by its index, which is a reference to the item’s position in the array. In most languages, the first item is at index 0:

 
colors = [​"Red"​, ​"Green"​, ​"Blue"​];
 
console.log(colors[0]);
 
>> ​"Red"

A map is a data structure that maps keys to values, and you retrieve data by the key rather than the position:

 
person = {name: ​"Homer"​, age: 42};
 
console.log person[​"name"​];

One of the most common uses of data structures is representing a collection of records from a database. Each record is represented by a map, with each field being a name/value pair within the map. The collection of records is represented by an array.

Here’s an example in JavaScript:

 
var​ people = [
 
{name: ​"Homer"​, age: 42},
 
{name: ​"Barney"​, age: 41}
 
]

And here’s the same structure, but written in Elixir:

 
people = [
 
%{name: ​"Homer"​, age: 42},
 
%{name: ​"Barney"​, age: 41}
 
]

While the syntax is different, the concept is the same; you use data structures to store similar data so you can use it in your programs.

Data structures are often used in conjunction with loops. For example, if you had a list of names and you wanted to print each one, you would iterate over the collection and sum up the values. Here’s a quick example in JavaScript using a for loop:

 
var​ names = [​"Ted"​, ​"Barney"​, ​"Carl"​, ​"Tracy"​];
 
for​(​var​ i = 0, length = names.length; i < length; i++) {
 
console.log(names[i]);
 
}

However, many languages offer an alternative approach. In Ruby, you can write the same code like this:

 
names = [​"Ted"​, ​"Barney"​, ​"Carl"​, ​"Tracy"​]
 
names.each { |name| puts name }

Elixir offers a similar approach:

 
names = [​"Ted"​, ​"Barney"​, ​"Carl"​, ​"Tracy"​]
 
names
 
|> Enum.each ​fn​(name) -> IO.puts name ​end

Java, C#, JavaScript, and many other languages have lots of features for iterating, sorting, and manipulating lists and other data structures. So as you work through this chapter, look up how to work with these concepts and use what you learn to solve the problems in this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.74.199