Array iterators and working through nested objects and arrays
One of the more challenging concepts that we’ve learned while studying Javascript is iteration. Iteration is basically going through an object or array and performing a function on all the individual elements of the the object or array to change the data structures in a certain way. Objects are organized by key-value pairs, while array’s are organized by indexes. The index of the first element in an array starts at zero or [0], and the next is [1] and so on.
The most basic way to iterate over objects and arrays are to use loops. For objects, we use what is called a for…in loop.
MDN gives us the following example. Notice that the for…in loop is iterating through the individual keys of the object. Here each key is assigned the variable, “property”. The for…in loop is trying to console.log both the key and the corresponding value so there are some additional steps. In order to access the values of each key, we have to use bracket notation, as seen by “object[property]”. We used bracket notation instead of dot notation because “property” is a variable and not the name of a key. Also notice the usage of the backticks and the interpolation. The backticks allow us add additional string elements such as the colon, and the interpolation inserts the variables into the string. Once again, we are iterating over each key within the object in order.
The most basic way to iterate over an array is using a for…of loop.
MDN gives the following example. A for…of loop allows you to iterate through an array or array-like object including a string in the order of each index. Here the for…of loop is logging each element of array1 into the console as can be seen by lines 7–9.
The forEach() method can be used similarly to a for of loop but it’s only used on arrays. The syntax is also different
MDN provides the follow example. The method forEach() is invoked on the array, and the parameter is a callback function that targets each individual element of the array in the order of their index.
Other array methods include find, filter, map, and reduce. Find returns the first element that matches the condition given in the callback. If no elements match the condition, undefined is returned. Filter returns a new array with all the elements that match the condition given in the call back. Map creates a new array with all the elements of the original array after they have been changed by a function given in the callback. Reduce, aggregates usually an array of numbers into a total.
Flatiron has a lab called hashketball that gets students to practice these concepts using a nested object with arrays. The nested object given is as follows.
gameObject is a function that contains the nested objects with the keys of home and away. Home and away contain an object made up of keys of teamName colors and players. teamName contains a string. Colors contains an array of colors. Players contains an array of objects with keys of playerName, number, shoe, points, rebounds, assists, steals, blocks, and slamDunks.
One of the challenges asks to build a function called numPointsScored that takes in an argument of a player’s name and returns the number of points scored for that player.
So in order to this we must first realize that we need to use the find function because it will match the player name in the argument, with the player name in the array.
We also need an array with all the playerNames that the find function will be invoked on. In the function the playerNames are divided into Away and Home, so the most efficient solution would require us to combine them into a single array.
One of my initial thoughts on how to solve the playerName solution was to create a new empty array and push all the playerNames into the array using an iterator. However we still need the information that is tied to the players key because we need to return the player points.
Instead of pushing the players into a new array we can do the same thing using a spread operator. The spread operator or “…” will allow us to copy an array and add it to a new array.
const players = () => [...gameObject().home.players, ...gameObject().away.players]
We set a variable to the new array called players. The dot notation allows us to access the property players. Players is within home and away which is within gameObject(). This combines the players from home and away which contains an array of objects with the information we need of playerName and points.
In order to match the playerNames with the argument, we need to use the find method as follows.
const player = (name) => players().find(player => player.playerName === name)
The return value is the object under players which contains the playerName, number, shoe, points, rebounds, assists, steals, blocks, and slamDunks.
In order to return the points of the matching player, we use the following code.
const numPointsScored = (name) => {
return player(name).points
}
This runs the find function that we defined as “player” on the “name” which is the argument, and returns the points of the matching playerName.
There are even tougher challenges in the lab such as
Which player has the most points? Call the function mostPointsScored.
Which team has the most points? Call the function winningTeam.
Which player has the longest name? Call the function playerWithLongestName.
These can be tackled with a similar approach. Ask yourself what iterator methods you would need, how would you organize the information, how you will access the information you need within the nested object, and how you would make the coding concise. I will not be going over how to solve the whole lab to not spoil it. As you can see, iteration can be a tough topic especially when it involves nested information.
No comments:
Post a Comment