GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||
GeezerVison is showing eloquentjavascript.net — Data Structures: Objects and Arrays :: Eloquent JavaScript Data Structures: Objects and Arrays
![]() Numbers, Booleans, and strings are the atoms from which data structures are built. Many types of information require more than one atom, though. Objects allow us to group values—including other objects—to build more complex structures. The programs we have built so far have been limited by the fact that they were operating only on simple data types. After learning the basics of data structures in this chapter, you’ll know enough to start writing useful programs. The chapter will work through a more or less realistic programming example, introducing concepts as they apply to the problem at hand. The example code will often build on functions and bindings introduced earlier in the book. The weresquirrelEvery now and then, usually between 8 p.m. and 10 p.m., Jacques finds himself transforming into a small furry rodent with a bushy tail. On one hand, Jacques is quite glad that he doesn’t have classic lycanthropy. Turning into a squirrel does cause fewer problems than turning into a wolf. Instead of having to worry about accidentally eating the neighbor (that would be awkward), he worries about being eaten by the neighbor’s cat. After two occasions of waking up on a precariously thin branch in the crown of an oak, naked and disoriented, he has taken to locking the doors and windows of his room at night and putting a few walnuts on the floor to keep himself busy. But Jacques would prefer to get rid of his condition entirely. The irregular occurrences of the transformation make him suspect that they might be triggered by something. For a while, he believed that it happened only on days when he had been near oak trees. However, avoiding oak trees did not solve the problem. Switching to a more scientific approach, Jacques has started keeping a daily log of everything he does on a given day and whether he changed form. With this data he hopes to narrow down the conditions that trigger the transformations. The first thing he needs is a data structure to store this information. DatasetsTo work with a chunk of digital data, we first have to find a way to represent it in our machine’s memory. Say, for example, that we want to represent a collection of the numbers 2, 3, 5, 7, and 11. We could get creative with strings—after all, strings can have any length, so we can put a lot of data into them—and use Fortunately, JavaScript provides a data type specifically for storing sequences of values. It is called an array and is written as a list of values between square brackets, separated by commas. let listOfNumbers = [2, 3, 5, 7, 11]; console.log(listOfNumbers[2]); // → 5 console.log(listOfNumbers[0]); // → 2 console.log(listOfNumbers[2 - 1]); // → 3 The notation for getting at the elements inside an array also uses square brackets. A pair of square brackets immediately after an expression, with another expression inside of them, will look up the element in the left-hand expression that corresponds to the index given by the expression in the brackets. The first index of an array is zero, not one, so the first element is retrieved with PropertiesWe’ve seen a few expressions like Almost all JavaScript values have properties. The exceptions are null.length; // → TypeError: null has no properties The two main ways to access properties in JavaScript are with a dot and with square brackets. Both If you know that the property in which you are interested is called color, you say The elements in an array are stored as the array’s properties, using numbers as property names. Because you can’t use the dot notation with numbers and usually want to use a binding that holds the index anyway, you have to use the bracket notation to get at them. Just like strings, arrays have a MethodsBoth string and array values contain, in addition to the let doh = "Doh"; console.log(typeof doh.toUpperCase); // → function console.log(doh.toUpperCase()); // → DOH Every string has a Interestingly, even though the call to Properties that contain functions are generally called methods of the value they belong to, as in “ This example demonstrates two methods you can use to manipulate arrays. let sequence = [1, 2, 3]; sequence.push(4); sequence.push(5); console.log(sequence); // → [1, 2, 3, 4, 5] console.log(sequence.pop()); // → 5 console.log(sequence); // → [1, 2, 3, 4] The These somewhat silly names are the traditional terms for operations on a stack. A stack, in programming, is a data structure that allows you to push values into it and pop them out again in the opposite order so that the thing that was added last is removed first. Stacks are common in programming—you might remember the function call stack from the previous chapter, which is an instance of the same idea. ObjectsBack to the weresquirrel. A set of daily log entries can be represented as an array, but the entries do not consist of just a number or a string—each entry needs to store a list of activities and a Boolean value that indicates whether Jacques turned into a squirrel or not. Ideally, we would like to group these together into a single value and then put those grouped values into an array of log entries. Values of the type object are arbitrary collections of properties. One way to create an object is by using braces as an expression. let day1 = { squirrel: false, events: ["work", "touched tree", "pizza", "running"] }; console.log(day1.squirrel); // → false console.log(day1.wolf); // → undefined day1.wolf = false; console.log(day1.wolf); // → false Inside the braces, you write a list of properties separated by commas. Each property has a name followed by a colon and a value. When an object is written over multiple lines, indenting it as shown in this example helps with readability. Properties whose names aren’t valid binding names or valid numbers must be quoted: let descriptions = { work: "Went to work", "touched tree": "Touched a tree" }; This means that braces have two meanings in JavaScript. At the start of a statement, they begin a block of statements. In any other position, they describe an object. Fortunately, it is rarely useful to start a statement with an object in braces, so the ambiguity between these two is not much of a problem. The one case where this does come up is when you want to return an object from a shorthand arrow function—you can’t write Reading a property that doesn’t exist will give you the value It is possible to assign a value to a property expression with the To briefly return to our tentacle model of bindings—property bindings are similar. They grasp values, but other bindings and properties might be holding onto those same values. You can think of objects as octopuses with any number of tentacles, each of which has a name written on it. The let anObject = {left: 1, right: 2}; console.log(anObject.left); // → 1 delete anObject.left; console.log(anObject.left); // → undefined console.log("left" in anObject); // → false console.log("right" in anObject); // → true The binary To find out what properties an object has, you can use the console.log(Object.keys({x: 0, y: 0, z: 2})); // → ["x", "y", "z"] There’s an let objectA = {a: 1, b: 2}; Object.assign(objectA, {b: 3, c: 4}); console.log(objectA); // → {a: 1, b: 3, c: 4} Arrays, then, are just a kind of object specialized for storing sequences of things. If you evaluate Jacques will represent the journal that Jacques keeps as an array of objects: let journal = [ {events: ["work", "touched tree", "pizza", "running", "television"], squirrel: false}, {events: ["work", "ice cream", "cauliflower", "lasagna", "touched tree", "brushed teeth"], squirrel: false}, {events: ["weekend", "cycling", "break", "peanuts", "beer"], squirrel: true}, /* And so on... */ ]; MutabilityWe will get to actual programming soon, but first, there’s one more piece of theory to understand. We saw that object values can be modified. The types of values discussed in earlier chapters, such as numbers, strings, and Booleans, are all immutable—it is impossible to change values of those types. You can combine them and derive new values from them, but when you take a specific string value, that value will always remain the same. The text inside it cannot be changed. If you have a string that contains Objects work differently. You can change their properties, causing a single object value to have different content at different times. When we have two numbers, 120 and 120, we can consider them precisely the same number, whether or not they refer to the same physical bits. With objects, there is a difference between having two references to the same object and having two different objects that contain the same properties. Consider the following code: let object1 = {value: 10}; let object2 = object1; let object3 = {value: 10}; console.log(object1 == object2); // → true console.log(object1 == object3); // → false object1.value = 15; console.log(object2.value); // → 15 console.log(object3.value); // → 10 The Bindings can also be changeable or constant, but this is separate from the way their values behave. Even though number values don’t change, you can use a const score = {visitors: 0, home: 0}; // This is okay score.visitors = 1; // This isn't allowed score = {visitors: 1, home: 1}; When you compare objects with JavaScript’s The lycanthrope’s logJacques starts up his JavaScript interpreter and sets up the environment he needs to keep his journal: let journal = []; function addEntry(events, squirrel) { journal.push({events, squirrel}); } Note that the object added to the journal looks a little odd. Instead of declaring properties like Every evening at 10 p.m.—or sometimes the next morning, after climbing down from the top shelf of his bookcase—Jacques records the day: addEntry(["work", "touched tree", "pizza", "running", "television"], false); addEntry(["work", "ice cream", "cauliflower", "lasagna", "touched tree", "brushed teeth"], false); addEntry(["weekend", "cycling", "break", "peanuts", "beer"], true); Once he has enough data points, he intends to use statistics to find out which of these events may be related to the squirrelifications. Correlation is a measure of dependence between statistical variables. A statistical variable is not quite the same as a programming variable. In statistics you typically have a set of measurements, and each variable is measured for every measurement. Correlation between variables is usually expressed as a value that ranges from -1 to 1. Zero correlation means the variables are not related. A correlation of 1 indicates that the two are perfectly related—if you know one, you also know the other. Negative 1 also means that the variables are perfectly related but are opposites—when one is true, the other is false. To compute the measure of correlation between two Boolean variables, we can use the phi coefficient (ϕ). This is a formula whose input is a frequency table containing the number of times the different combinations of the variables were observed. The output of the formula is a number between -1 and 1 that describes the correlation. We could take the event of eating pizza and put that in a frequency table like this, where each number indicates the number of times that combination occurred in our measurements. If we call that table n, we can compute ϕ using the following formula:
(If at this point you’re putting the book down to focus on a terrible flashback to 10th grade math class—hold on! I do not intend to torture you with endless pages of cryptic notation—it’s just this one formula for now. And even with this one, all we do is turn it into JavaScript.) The notation n01 indicates the number of measurements where the first variable (squirrelness) is false (0) and the second variable (pizza) is true (1). In the pizza table, n01 is 9. The value n1• refers to the sum of all measurements where the first variable is true, which is 5 in the example table. Likewise, n•0 refers to the sum of the measurements where the second variable is false. So for the pizza table, the part above the division line (the dividend) would be 1×76−4×9 = 40, and the part below it (the divisor) would be the square root of 5×85×10×80, or √340,000. This comes out to ϕ ≈ 0.069, which is tiny. Eating pizza does not appear to have influence on the transformations. Computing correlationWe can represent a two-by-two table in JavaScript with a four-element array ( This is the function that computes the ϕ coefficient from such an array: function phi(table) { return (table[3] * table[0] - table[2] * table[1]) / Math.sqrt((table[2] + table[3]) * (table[0] + table[1]) * (table[1] + table[3]) * (table[0] + table[2])); } console.log(phi([76, 9, 4, 1])); // → 0.068599434 This is a direct translation of the ϕ formula into JavaScript. Jacques keeps his journal for three months. The resulting dataset is available in the coding sandbox for this chapter, where it is stored in the To extract a two-by-two table for a specific event from the journal, we must loop over all the entries and tally how many times the event occurs in relation to squirrel transformations: function tableFor(event, journal) { let table = [0, 0, 0, 0]; for (let i = 0; i < journal.length; i++) { let entry = journal[i], index = 0; if (entry.events.includes(event)) index += 1; if (entry.squirrel) index += 2; table[index] += 1; } return table; } console.log(tableFor("pizza", JOURNAL)); // → [76, 9, 4, 1] Arrays have an The body of the loop in We now have the tools we need to compute individual correlations. The only step remaining is to find a correlation for every type of event that was recorded and see whether anything stands out. Array loopsIn the for (let i = 0; i < JOURNAL.length; i++) { let entry = JOURNAL[i]; // Do something with entry } This kind of loop is common in classical JavaScript—going over arrays one element at a time is something that comes up a lot, and to do that you’d run a counter over the length of the array and pick out each element in turn. There is a simpler way to write such loops in modern JavaScript: for (let entry of JOURNAL) { console.log(`${entry.events.length} events.`); } When a The final analysisWe need to compute a correlation for every type of event that occurs in the dataset. To do that, we first need to find every type of event. function journalEvents(journal) { let events = []; for (let entry of journal) { for (let event of entry.events) { if (!events.includes(event)) { events.push(event); } } } return events; } console.log(journalEvents(JOURNAL)); // → ["carrot", "exercise", "weekend", "bread", …] By adding any event names that aren’t already in it to the Using that function, we can see all the correlations: for (let event of journalEvents(JOURNAL)) { console.log(event + ":", phi(tableFor(event, JOURNAL))); } // → carrot: 0.0140970969 // → exercise: 0.0685994341 // → weekend: 0.1371988681 // → bread: -0.0757554019 // → pudding: -0.0648203724 // And so on... Most correlations seem to lie close to zero. Eating carrots, bread, or pudding apparently does not trigger squirrel-lycanthropy. The transformations do seem to occur somewhat more often on weekends. Let’s filter the results to show only correlations greater than 0.1 or less than -0.1: for (let event of journalEvents(JOURNAL)) { let correlation = phi(tableFor(event, JOURNAL)); if (correlation > 0.1 || correlation < -0.1) { console.log(event + ":", correlation); } } // → weekend: 0.1371988681 // → brushed teeth: -0.3805211953 // → candy: 0.1296407447 // → work: -0.1371988681 // → spaghetti: 0.2425356250 // → reading: 0.1106828054 // → peanuts: 0.5902679812 Aha! There are two factors with a correlation clearly stronger than the others. Eating peanuts has a strong positive effect on the chance of turning into a squirrel, whereas brushing teeth has a significant negative effect. Interesting. Let’s try something. for (let entry of JOURNAL) { if (entry.events.includes("peanuts") && !entry.events.includes("brushed teeth")) { entry.events.push("peanut teeth"); } } console.log(phi(tableFor("peanut teeth", JOURNAL))); // → 1 That’s a strong result. The phenomenon occurs precisely when Jacques eats peanuts and fails to brush his teeth. If only he weren’t such a slob about dental hygiene, he’d never even have noticed his affliction. Knowing this, Jacques stops eating peanuts altogether and finds that his transformations stop. But it takes only a few months for him to notice that something is missing from this entirely human way of living. Without his feral adventures, Jacques hardly feels alive at all. He decides he’d rather be a full-time wild animal. After building a beautiful little tree house in the forest and equipping it with a peanut butter dispenser and a ten-year supply of peanut butter, he changes form one last time, and lives the short and energetic life of a squirrel. Further arrayologyBefore finishing the chapter, I want to introduce you to a few more object-related concepts. I’ll start with some generally useful array methods. We saw let todoList = []; function remember(task) { todoList.push(task); } function getTask() { return todoList.shift(); } function rememberUrgently(task) { todoList.unshift(task); } This program manages a queue of tasks. You add tasks to the end of the queue by calling To search for a specific value, arrays provide an console.log([1, 2, 3, 2, 1].indexOf(2)); // → 1 console.log([1, 2, 3, 2, 1].lastIndexOf(2)); // → 3 Both Another fundamental array method is console.log([0, 1, 2, 3, 4].slice(2, 4)); // → [2, 3] console.log([0, 1, 2, 3, 4].slice(2)); // → [2, 3, 4] When the end index is not given, The The following example shows both function remove(array, index) { return array.slice(0, index) .concat(array.slice(index + 1)); } console.log(remove(["a", "b", "c", "d", "e"], 2)); // → ["a", "b", "d", "e"] If you pass Strings and their propertiesWe can read properties like let kim = "Kim"; kim.age = 88; console.log(kim.age); // → undefined Values of type string, number, and Boolean are not objects, and though the language doesn’t complain if you try to set new properties on them, it doesn’t actually store those properties. As mentioned earlier, such values are immutable and cannot be changed. But these types do have built-in properties. Every string value has a number of methods. Some very useful ones are console.log("coconuts".slice(4, 7)); // → nut console.log("coconut".indexOf("u")); // → 5 One difference is that a string’s console.log("one two three".indexOf("ee")); // → 11 The console.log(" okay \n ".trim()); // → okay The console.log(String(6).padStart(3, "0")); // → 006 You can split a string on every occurrence of another string with let sentence = "Secretarybirds specialize in stomping"; let words = sentence.split(" "); console.log(words); // → ["Secretarybirds", "specialize", "in", "stomping"] console.log(words.join(". ")); // → Secretarybirds. specialize. in. stomping A string can be repeated with the console.log("LA".repeat(3)); // → LALALA We have already seen the string type’s let string = "abc"; console.log(string.length); // → 3 console.log(string[1]); // → b Rest parametersIt can be useful for a function to accept any number of arguments. For example, function max(...numbers) { let result = -Infinity; for (let number of numbers) { if (number > result) result = number; } return result; } console.log(max(4, 1, 9, -2)); // → 9 When such a function is called, the rest parameter is bound to an array containing all further arguments. If there are other parameters before it, their values aren’t part of that array. When, as in You can use a similar three-dot notation to call a function with an array of arguments. let numbers = [5, 1, 7]; console.log(max(...numbers)); // → 7 This “spreads” out the array into the function call, passing its elements as separate arguments. It is possible to include an array like that along with other arguments, as in Square bracket array notation similarly allows the triple-dot operator to spread another array into the new array: let words = ["never", "fully"]; console.log(["will", ...words, "understand"]); // → ["will", "never", "fully", "understand"] This works even in curly brace objects, where it adds all properties from another object. If a property is added multiple times, the last value to be added wins: let coordinates = {x: 10, y: 0}; console.log({...coordinates, y: 5, z: 1}); // → {x: 10, y: 5, z: 1} The Math objectAs we’ve seen, The Having too many global bindings “pollutes” the namespace. The more names have been taken, the more likely you are to accidentally overwrite the value of some existing binding. For example, it’s not unlikely you’ll want to name something Many languages will stop you, or at least warn you, when you are defining a binding with a name that is already taken. JavaScript does this for bindings you declared with Back to the function randomPointOnCircle(radius) { let angle = Math.random() * 2 * Math.PI; return {x: radius * Math.cos(angle), y: radius * Math.sin(angle)}; } console.log(randomPointOnCircle(2)); // → {x: 0.3667, y: 1.966} If you’re not familiar with sines and cosines, don’t worry. I’ll explain them when they are used in Chapter 14. The previous example used console.log(Math.random()); // → 0.36993729369714856 console.log(Math.random()); // → 0.727367032552138 console.log(Math.random()); // → 0.40180766698904335 Though computers are deterministic machines—they always react the same way if given the same input—it is possible to have them produce numbers that appear random. To do that, the machine keeps some hidden value, and whenever you ask for a new random number, it performs complicated computations on this hidden value to create a new value. It stores a new value and returns some number derived from it. That way, it can produce ever new, hard-to-predict numbers in a way that seems random. If we want a whole random number instead of a fractional one, we can use console.log(Math.floor(Math.random() * 10)); // → 2 Multiplying the random number by 10 gives us a number greater than or equal to 0 and below 10. Since There are also the functions DestructuringLet’s return to the function phi(table) { return (table[3] * table[0] - table[2] * table[1]) / Math.sqrt((table[2] + table[3]) * (table[0] + table[1]) * (table[1] + table[3]) * (table[0] + table[2])); } One reason this function is awkward to read is that we have a binding pointing at our array, but we’d much prefer to have bindings for the elements of the array—that is, function phi([n00, n01, n10, n11]) { return (n11 * n00 - n10 * n01) / Math.sqrt((n10 + n11) * (n00 + n01) * (n01 + n11) * (n00 + n10)); } This also works for bindings created with A similar trick works for objects, using braces instead of square brackets. let {name} = {name: "Faraji", age: 23}; console.log(name); // → Faraji Note that if you try to destructure Optional property accessWhen you aren’t sure whether a given value produces an object, but still want to read a property from it when it does, you can use a variant of the dot notation: function city(object) { return object.address?.city; } console.log(city({address: {city: "Toronto"}})); // → Toronto console.log(city({name: "Vera"})); // → undefined The expression A similar notation can be used with square bracket access, and even with function calls, by putting console.log("string".notAMethod?.()); // → undefined console.log({}.arrayProp?.[0]); // → undefined JSONBecause properties grasp their value rather than contain it, objects and arrays are stored in the computer’s memory as sequences of bits holding the addresses—the place in memory—of their contents. An array with another array inside of it consists of (at least) one memory region for the inner array and another for the outer array, containing (among other things) a number that represents the address of the inner array. If you want to save data in a file for later or send it to another computer over the network, you have to somehow convert these tangles of memory addresses to a description that can be stored or sent. You could send over your entire computer memory along with the address of the value you’re interested in, I suppose, but that doesn’t seem like the best approach. What we can do is serialize the data. That means it is converted into a flat description. A popular serialization format is called JSON (pronounced “Jason”), which stands for JavaScript Object Notation. It is widely used as a data storage and communication format on the web, even with languages other than JavaScript. JSON looks similar to JavaScript’s way of writing arrays and objects, with a few restrictions. All property names have to be surrounded by double quotes, and only simple data expressions are allowed—no function calls, bindings, or anything that involves actual computation. Comments are not allowed in JSON. A journal entry might look like this when represented as JSON data: { "squirrel": false, "events": ["work", "touched tree", "pizza", "running"] } JavaScript gives us the functions let string = JSON.stringify({squirrel: false, events: ["weekend"]}); console.log(string); // → {"squirrel":false,"events":["weekend"]} console.log(JSON.parse(string).events); // → ["weekend"] SummaryObjects and arrays provide ways to group several values into a single value. This allows us to put a bunch of related things in a bag and run around with the bag instead of wrapping our arms around all of the individual things and trying to hold on to them separately. Most values in JavaScript have properties, with the exceptions being There are some named properties in arrays, such as You can iterate over arrays using a special kind of ExercisesThe sum of a rangeThe introduction of this book alluded to the following as a nice way to compute the sum of a range of numbers: console.log(sum(range(1, 10))); Write a Next, write a As a bonus assignment, modify your // Your code here. console.log(range(1, 10)); // → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] console.log(range(5, 2, -1)); // → [5, 4, 3, 2] console.log(sum(range(1, 10))); // → 55 Display hints...Building up an array is most easily done by first initializing a binding to Since the end boundary is inclusive, you’ll need to use the The step parameter can be an optional parameter that defaults (using the Having It might also be worthwhile to use a different default step, namely, -1, when the end of the range is smaller than the start. That way, Reversing an arrayArrays have a Thinking back to the notes about side effects and pure functions in the previous chapter, which variant do you expect to be useful in more situations? Which one runs faster? // Your code here. let myArray = ["A", "B", "C"]; console.log(reverseArray(myArray)); // → ["C", "B", "A"]; console.log(myArray); // → ["A", "B", "C"]; let arrayValue = [1, 2, 3, 4, 5]; reverseArrayInPlace(arrayValue); console.log(arrayValue); // → [5, 4, 3, 2, 1] Display hints...There are two obvious ways to implement Reversing the array in place is harder. You have to be careful not to overwrite elements that you will later need. Using The trick is to swap the first and last elements, then the second and second-to-last, and so on. You can do this by looping over half the length of the array (use A listAs generic blobs of values, objects can be used to build all sorts of data structures. A common data structure is the list (not to be confused with arrays). A list is a nested set of objects, with the first object holding a reference to the second, the second to the third, and so on: let list = { value: 1, rest: { value: 2, rest: { value: 3, rest: null } } }; The resulting objects form a chain, as shown in the following diagram: A nice thing about lists is that they can share parts of their structure. For example, if I create two new values Write a function If you haven’t already, also write a recursive version of // Your code here. console.log(arrayToList([10, 20])); // → {value: 10, rest: {value: 20, rest: null}} console.log(listToArray(arrayToList([10, 20, 30]))); // → [10, 20, 30] console.log(prepend(10, prepend(20, null))); // → {value: 10, rest: {value: 20, rest: null}} console.log(nth(arrayToList([10, 20, 30]), 1)); // → 20 Display hints...Building up a list is easier when done back to front. So To run over a list (in for (let node = list; node; node = node.rest) {} Can you see how that works? Every iteration of the loop, The recursive version of Deep comparisonThe Write a function To find out whether values should be compared directly (using the The // Your code here. let obj = {here: {is: "an"}, object: 2}; console.log(deepEqual(obj, obj)); // → true console.log(deepEqual(obj, {here: 1, object: 2})); // → false console.log(deepEqual(obj, {here: {is: "an"}, object: 2})); // → true Display hints...Your test for whether you are dealing with a real object will look something like Use Returning the correct value from the function is best done by immediately returning | ||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |