Key for JavaScript: Arrays Review PDF
Document Details
![FastPacedLightYear](https://quizgecko.com/images/avatars/avatar-3.webp)
Uploaded by FastPacedLightYear
Tags
Summary
This document provides a review of JavaScript arrays, covering key methods such as push, pop, shift, and splice. It includes practice questions on array manipulation and callback functions, offering a solid foundation for understanding and working with arrays in JavaScript.
Full Transcript
Key for JavaScript: Arrays Review (Last One) Here's the last review before the quiz. The quiz will be eerily similar to the format and style you see here. Short Answer In addition to answering the questions posed, circle modified or unmodified to indicate whether or not the method has the ability...
Key for JavaScript: Arrays Review (Last One) Here's the last review before the quiz. The quiz will be eerily similar to the format and style you see here. Short Answer In addition to answering the questions posed, circle modified or unmodified to indicate whether or not the method has the ability to modify the contents of the array. 1. Briefly describe what the push() and pop() methods do. Be sure to address how this is different from the answer to question 2. modified/unmodified The push() function allows you to add items to the end of an array; it takes a parameter, the item to add. The pop() function removes and returns the last element of the array. Both modify. 2. Briefly describe what the shift() and unshift() methods do. Your answer here should make it clear how these are different from what push() and pop() do. modified/unmodified These are similar to push() and pop() but deal with the front of the array, sliding elements over every time it adds or removes to/from the front of the array. The both modify. 3. Briefly describe the two main uses of the splice() function. The generic parameters to splice are: pos, numb, item1, item2, … Address what these represent in your answer, using the names shown here for clarity. modified/unmodified The splice() function is used to add and/or remove elements from a position, indicated by pos. The numb parameter is how many elements to remove (starting at position pos). If this is 0, then nothing is removed. If elements are removed, any remaining elements on the right are shifted over to cover the gaps left by the removal. The itemX parameters are the items to be inserted at position pos. Elements in positions pos or greater are shifted over to the right to make room for these new items. If there are no parameters after the first two, then nothing is inserted into the list. 4. Briefly describe what the slice() method does. The generic parameters for this function are: start, end Be sure to address how these parameters are involved in obtaining the output. modified/unmodified The slice() method simply returns a sub-array (like a substring). This sub-array starts at position start, and includes the element in that position, and stops at position end (but does NOT include the element in position end). This does not modify the original array at all. 5. Briefly describe what the indexOf(), lastIndexOf(), and includes() methods do. The generic parameters to these functions are: item, startPos What does the first parameter represent (relative to items in the array)? The item parameter is an item in the array to search for. These methods check if any element in the array is equal to item; the includes method returns a boolean, and the other two return the position of the item found (or -1 if not found). The second parameter is frequently ignored or not included when using these methods. What does the second parameter do or represent if you do include it? By default, these functions start at position 0 (or the last position of the array for lastIndexOf) and then seek the desired item. The optional startPos parameter gives you the ability to start at a different starting position…for example, if you already found the first item in position 4, you could keep looking and use a second parameter of 5 so that you start your search after the one that you already located. This would typically be done in a loop…or you could not do this and use the filter method instead to find all matches (these methods only return the first match found). modified/unmodified 6. What is a callback function? A callback function is a function sent as a parameter to another function (that I'll call that the invoked function). When the invoked function is doing its thing, it will use the callback function as part of its work. The invoked function will call the callback function at some point. Designing with callback functions (writing methods that accept callback functions) creates flexible design patterns. Here is a quick example, a function that takes a generic "how should I display this" as a second parameter, a callback function. function doSomethingMathy( value, displayFunction ) { //generic callback function //pretend we do some math and calculate a value based off the parameter value let x = … //some value //now let's display that using our displayFunction displayFunction( x ) //we use this function } When we use doSomethingMathy(), we'll need to send it a function that can display a value. Here are a couple of ways that we can write a function to display a value. function useAnAlert( numb ) { alert( numb ) } function useHTML( numb ) { document.getElementById("someParagraph").innerHTML = numb } function useTheConsole( numb ) { console.log("Value received: " + numb ) } Now…to use doSomethingMathy(), we simply send it the name of which display function we are interested in. doSomethingMathy( 100, useAlert ) doSomethingMathy( 100, useHTML ) doSomethingMathy( 100, useTheConsole ) 7. Related to indexOf(), lastIndexOf(), and includes() are the findIndex(), findLastIndex(), and find() methods. However, these functions take a fundamentally different parameter: a callback function. What is that parameter (what does it represent) and how are these methods (find(), findIndex(), findLastIndex()) more powerful or flexible? Come up with an example of a list of objects (some complicated object…not just a list of numbers) where indexOf() will not find the object you want but findIndex() could work. modified/unmodified When using indexOf(), lastIndexOf(), and includes(), you must send a parameter to the method. This parameter represents some element in the array that you are searching for; these methods check to see if any element in the array is equal to the parameter you send. However, with find(), findIndex(), and findLastIndex(), you have more power and flexibility. You write a callback function that returns true for the element that you are searching for. Rather than checking for equality only, your callback function can check for any property or combination of properties that you are interested in. For example, let's say you have a list of strings. You can use indexOf() to search for any particular string, but you can't focus on properties of the string; you couldn't use indexOf() to search for a string of length 5, for example. However, you can accomplish this with findIndex(); you simply write (and pass along) a callback function that returns true if the element passed to it has a length of 5. Similarly…imagine that you have a list of Book objects. You can use findIndex() to search for the first book written by a particular author (you can write a callback function that returns true when an element has a particular author). 8. Related to the above methods, and yet importantly different, is the filter() method. This also accepts a callback function as its parameter. What does the filter() method do (what is the goal of using the filter() method)? What does the method return (and, importantly, how is that different from the method discussed in problem 5 and 7)? modified/unmodified The above methods (indexOf(), lastIndexOf(), findIndex(), and findLastIndex()) return the position of the first element found and only one the first position found (or -1 if not found). The filter() method is designed to return ALL elements found (all elements that satisfy the callback function you pass to filter()). The "index" methods return a position for a single element (or -1 if nothing is found); filter() returns an array containing all items that satisfied the callback function (an array of all elements where the callback function returned true when sent the element). 9. Briefly describe the purpose of the map() method. What does the map() method return? modified/unmodified The map() method transforms each element of your array into some other element; each element in the starting array is "mapped" to a new element in the output array. You could use the map() method to turn a list of Student objects into a simple list of strings (the first names of the students). Or you could turn a list of Game objects (games that your team has played this season) into a simple list of "win", "loss", "tie", or "not yet" strings, corresponding to the output of each game (where "not yet" indicates a game that has yet to be played). The map() method, in general, is a nice way to turn an array of Blahs into a corresponding array of Foos. 10.So…the sort() method has a pretty clear purpose indicated by the name. However…what happens if you don't send a parameter to the sort() method (how will it attempt to sort your data)? What happens if your data isn't "the right type" for this approach? With no callback function, your data will be sorted alphabetically. Keep in mind that all uppercase letters are "less than" all lowercase letters, so "Zoo" comes before "apple" here. You could map your strings to all lowercase letters and then sort if that is an issue. If the objects aren't strings, then JS calls toString() on your object. If you provide your object a toString() (or if it has one), then that is how it will be sorted…by the string version of your objects. If you don't provide a toString() method, then the objects will not be sorted; you will get the default toString() behavior for all of your objects, which returns [object Object] (so all elements have the same string representation … not ideal). If you do send a callback function as a parameter…the callback function will receive two parameters. What do these parameters represent? How does the sort() method use that callback function (roughly…theoretically…we aren't going to look at the actual code to see exactly how/when/where it is used)? The callback function for sort is going to receive two parameters that represent any two elements of your array. To sort the array, the sort() method will use your callback function over and over, sending pairs of elements to the callback to determine which elements are bigger and which are smaller…shuffling the contents of the array until it is sorted. However, the only way that the sort() method knows which items are smaller or bigger is by sending pairs of items to our callback function. This gives us the ability to customize what it means to be "bigger" or "smaller". However, the sort() method just uses our callback function to do this…it "asks" our callback function which is the bigger of the two parameters. Quick Coding While these problems could be solved in many ways, the point here is to assess if you can use the techniques we have covered. You need to use the technique/method described. 11. Use the forEach() method to print only the even values in the given list of integers. Use console.log to do the printing. let list = //some list of integers…perhaps taken from a file list.forEach( (item) => { if( item%2 == 0 ) { console.log( item ); } }); 12. Given a list of Volunteer objects, use the map() method to create a list of numbers. These numbers correspond to the number of hours that each volunteer has worked. Assume that list contains Volunteer objects and that the Volunteer class has an hoursWorked property. let list = //some list of Volunteers //NOTE: YOU MUST SAVE THE MAPPED VALUES INTO A NEW VARIABLE…I AM SCREAMING let hours = list.map( (item) => item.hoursWorked ); 13. Given that same list of Volunteer objects, use the reduce() method to find the maximum number of hours worked by one Volunteer. Return the number of hours and save it in the variable maxHours. let list = //some list of Volunteers let maxHours = list.reduce( (accum, item) => { if( accum > item ) return accum; else return item; }); 14. Given that same list of Volunteers, use the filter() method to create an array of all Volunteers that have satisfied that Mandatory Fun Safety Training. Name this new array trained. Assume that the Volunteer class has a boolean property named trainingComplete that is only true if they have satisfied the Mandatory Fun Safety Training. let list = //some list of Volunteers let trained = list.filter( (item) => item.trainingComplete ); Reading Code What will the following code snippets output or produce? I'm looking for a description here rather than the actual contents of the array or the actual returned value. For example, if the code is finding the largest number in an array, then your answer might be "this finds the largest number in the array". 15. let list = //some list of strings Extra Question: sorted how? Ascending or descending order? list.sort() Sorted alphabetically, from "A" to "z" (ascending order) 16. let list = //some list of strings Extra Question: sorted how? Ascending or descending order? list.sort( (a, b) => a.length - b.length ) Sorted by length, ascending order (since we used a - b order). Shorter lengths to longer. It would be descending order (longer lengths first) if you did b.length - a.length. 17. TWO VERSIONS HERE. What do they do (generally) and how do they differ from each other? let list = //some list of products for sale on our website…assume that they have a price property list.sort( (a, b) => b.price - a.price ) Extra Question: Ascending or descending order? list.sort( (a, b) => a.price - b.price ) Extra Question: Ascending or descending order? These sort the products by their price…obviously. If you use a - b order, it is ascending. 18. let list1 = //some list of numbers let list2 = list1.map( (a) => a*a ) Maps list1 to a list of the numbers squared. So [3, -2, 5] maps to [9, 4, 25]. 19. let list1 = //some list of strings let list2 = list1.map( (a) => { if( a.length < 5 ) return "short"; else return a; }); The mapped list (list2) will contain all of the original strings in list1 as long as they have a length of 5 or more; for strings in list1 with a length less than 5, the mapped list contains "short" instead of the original string. So [ "a", "happy", "nope", "whatever" ] maps to [ "short", "happy", "short", "whatever" ] 20. let list1 = //some list of products on our website let list2 = list1.filter( (a) => a.price < 100 ) The list2 variable will include all elements from list1 where the price of the element is less than 100. 21. What type of thing is foo at the end of the day here? let list = //some list of products on our website…assume that they have a price property let foo = list.reduce( (acc, item) => { if(acc.price > item.price) return acc; else return item; }); We did not send anything as the starting value, so the first value of acc is the first item in our list, a product. We then compare the prices of products, but we ultimately return acc or item, meaning that we are returning an element from the list each time. So, foo will be a product; foo is not a number or a string, but rather a product object. 22. The reduce() method accepts an extra/optional parameter after the callback function. What does this optional parameter represent? What happens if you don't send one? The optional parameter after the callback function is the value that should be used as the first accumulator value, the value of the first parameter to the callback. If you do not provide a starting value for the accumulator, then the first time that reduce() is called you will receive the first element from the list as the accumulator and the second element from the list as the item parameter. If you do send a starting value, then the callback function is called for the first time with that starting value as the accumulator and the first element of the function as the item.