6. JS Arrays Público

6. JS Arrays

Kostas Diakogiannis
Curso por Kostas Diakogiannis, atualizado more than 1 year ago Colaboradores

Descrição

Js Intro to course to arrays. What are they used for and which the commonest methods are?

Informações do módulo

Sem etiquetas

Contexto

Course's Objectives 1. Learn the existence of a new data structure arrays. 2. Why are arrays used for? What kind of info can we store there? 3. How to access this info? What is the index of every array? 4. How to iterate through an array?  Which ways do they exist? 5. How to store new additional info. Which potential methods  arrays have? 6. If it's possible to have nested arrays and how to deal with them.
Mostrar menos
Sem etiquetas

Contexto

What is an array? Arrays are object type data structures in order to store multiple pieces of information in one place like normal objects. There are some key differences though: 1. Arrays are not a data type on their own. In reality they are objects. 2. They don't use a named index with keys and values but an index number, in order to store and retrieve info that begins from 0. This is index defines and reveals the position of a piece of info in the array. 3. Syntax also differs and square brackets are used instead of curly braces. Arrays are used mostly in order to store information into one place, information that is relevant to one thing and one thing only. For example all the test scores of the class, all the heights of the students etc. That does not mean that multiple data types cannot be stored of course. 4. Arrays can be iterated like objects. 5. Arrays have their own methods for manipulating, extracting and inserting data as well. 6. For more info check this one. On the example above you can see the creation of two arrays. In line number 4 we created an array that holds all the students' names of a single class. Below another array was created that holds information for a previous exercise regarding the creation of a cashier prototype. Although as you can see having different data types stored inside an array is possible, maybe it's not the most optimal way to do it, as it's not clear what these values represent due to the missing key that an object literal provides. So as general rule, is always preferable to use arrays for holding values, that is clear what they represent without having a key for identifying them. Otherwise we may want to go for object literals.
Mostrar menos
Sem etiquetas

Contexto

The length property Maybe the most commonly used property when working with arrays, is the length property. The length property of an array is used to reveal how many elements the checked array possesses.  Thus you can compare later if an array has more elements than another one etc. The value that is given back is a number (integer). In this case the belovedLanguages' length is 4, while hatedLanguages' length is 7.
Mostrar menos
Sem etiquetas

Contexto

A-1 More interesting person Create 2 arrays and store there the collection of hobbies for 2 people that you know. Eventually one of those can have potentially have more hobbies than the other one. Write a global function, the most re-usable way you can, that compares which one of them has the most hobbies and prints a message to the console ('John Doe is more interesting person than Jake Dack'). (Assuming that you know their names by heart, the arrays shouldn't contain any other piece of info than the hobbies themselves as strings).
Mostrar menos
Sem etiquetas

Contexto

Arrays index Index number  is the system that is being used in order to retrieve or store information from and into an array. Initial index begins at 0 as in almost all programming languages.  The syntax is simple: array[index] there. Where array is the variable's name or the array literally and the index the position of the element starting from 0. In the example above if we want to print out the 'bring these mountains' value to the console we can specify the name and pass number 2 as the index inside the square brackets (this will print whatever lies at third position of the array!). You can use the length property minus 1 if you want to get the last element of an array.
Mostrar menos
Sem etiquetas

Contexto

A-2 Candidate trainer Imagine that you are the manager of a school that teaches 5 topics. Math, science, history, geography and programming. For the first 4 topics you have already found the teachers to conduct the lessons and now you are actively looking for the fifth one. First of all create an object that holds the topics as keys and the fullname of the teacher as a string value. Thus you don't forget from now on who is going to teach what. Then create a method inside that object that accepts 2 arrays. These arrays contain the programming languages that candidates for the programming position have. The length of these languages can be anything. A candidate could have mastered 3 languages, the other one four. Just write these languages as strings inside the arrays. The first and second element of each of these arrays should contain the firstname and the lastname of each of the candidates as well. ex. const  Joe = ['John', 'Doe' , 'PHP', 'Ruby']; const Jane = ['Jane', 'Doe', 'Python', 'Java', 'C']; The method should compare, who knows more programming languages under his/her belt and puts his/her name in the fifth property of the object (under the other topics with their corresponding teachers).
Mostrar menos
Sem etiquetas

Contexto

Array iterating We can loop through each and one of array's elements as we did with objects. The only difference is the syntax since there are no keys to hold values. There are two ways for iterating through all arrays properties (more with new functions but for now we stick to these two). The classic for loop that uses a number for going through all indexes from 0 to array's length and the new for ... of loop which is equivalent to the for... in loop the normal objects have. Both are doing the exact same thing. On the first case, the classic for loop, we use the increment number i from 0 to the length of the array and then we use this number to as the index in order to access a new element every iteration. The ES6 for... of loop provides a more elegant syntax, as we don't have to specify an increment number and use it later as an index. We define a variable that represents the current element of the array at the given iteration. (similar to ES6 for...in for objects). The two loops in line 49 and 53, they perform exactly the same task.
Mostrar menos
Sem etiquetas

Contexto

A-3 Test Results problem Imagine that you are a teacher and you have collected the results from a test of your 10 students in one place. The test results are numbers from 1 to 100.  The basis is 50. Calculate what percentage of the class has not passed the basis. The results are the followed: 78, 82, 45, 69, 23, 91, 55, 39, 66, 60.
Mostrar menos
Sem etiquetas

Contexto

Array's methods Array's contain their own methods for storing, retrieving and manipulating data. Some of the most commonly used are: 1. Push - For adding a new element at the end of an array. 2. splice - adding or removing an element at a specified index position 3. concat - concatenating two arrays 4. indexOf - searches and returns the index of the element that holds this value 5. includes - searches if an element exists in an array and returns a boolean value. 6. Join - Joins all elements of the array into a single string by adding a specified string value in between. 7. pop - Removes the last element of an array and returns it. 8. shift - Removes the first element of the array and shifts the other elements. 9. unshift - Adds an element to the first position. Shift the other ones to a position next. 10. forEach - loops through all elements of an array and performs an action for each element. Accepts a function with three arguments that represent the value of each element, the index of it and the array itself respectively. The operation for each element is performed on the array itself. 11. map - Exactly the same as forEach, the only difference is that after performing the operation for each element, it pushes this element into a new array, at the end map returns a new array, that's why the whole map operation must be assigned into a new variable. 12. filter - accepts a function and filters an existing array based on the condition the function argument specifies. Like map returns a new array. Find out more array methods here! Attention: These are not the only array methods. Especially after ES2015 release, arrays come with a bunch of new, advanced and tremendously useful methods. We will see most of them alongside with corresponding problems and exercises inside the EcmaScript 6 section later on.
Mostrar menos
Sem etiquetas

Contexto

A-4 Fill the form.   Suppose you are a web developer teacher that teaches 3 different types of courses. 'JS course', 'PHP course' and 'Ruby course' in an online platform. You ask for feedback from 10 people that have taken various courses from you (but each person only one course).  Create an object for each client that holds student's full name in one property, his level of satisfaction from 1-100 from the services you have offered him and the product course he has bought from you. ex. {fullName: 'Kostas Diakogiannis', courseHasTaken: 'PHP Course', levelOfSatisfaction: 45} Create 10 objects like that and store them in an array called clients.  For every object add a new property that is going to be a string and it's value  depends on levelOfSatifaction value. For example if the levelOfSatisfaction is more than 80 add a new property with a name of stateOfHappy and assign to it a 'Found the course perfect'. For just more than 50 assign the value into it 'Content overall',  For 50 or lower, assign a value of  'Customer is complaining, potential refund is going to be asked'. After that, calculate the average satisfaction level per course. Store the results for each into an array and print the title of the course that has the biggest average of the three courses.
Mostrar menos
Sem etiquetas

Contexto

A-5 Hire or Not Imagine that you work currently as an HR manager in a company that wants to hire developers. The prerequisites for hiring someone is to know 3 of the 5 following programming languages. PHP, JavaScript, Ruby, Python and or Java. If the candidate has at least 3 of these 5 skills then he should be hire.  Create an array that holds the prerequisites. And a different array that holds every candidate's skills. Write a function so it can be re-usable for multiple pre-requisites and multiple candidates at the same time. Create an empty array to store the full name of the ones that got hired. If the guy is hired, push his name to the employed ones array. At the end this array is going to contain the names for every person that got hired. Hint: You may want to use the "includes" array method, which allows you to check if a specific value is included into an array or not and returns a boolean value. Check it here!
Mostrar menos
Sem etiquetas

Contexto

A-6 Test Results revisit Imagine that a fellow teacher has decided to split your results into two arrays of 5 length each. The one contains only scores from the ones that have passed and the other one from the ones that have not.  You didn't want that but you don't want to say something bad to him because you are friends and colleagues more years than someone can remember. The array that holds the good scores is [67, 82, 91, 96, 54]. The array that holds the bad scores is [46, 48, 24, 33, 30]. Find a way to unite these 2 arrays into one.  Possibly the concat function is going to be helpful at this point and you want to revisit it's documentation here. Calculate the average of  this unified array. Add a new element score (an 11th) to the new unified  array and recalculate the average again. Compare if the average has moved up, down and by what margin?  In the end try to find the best score in the class and print it to the console.
Mostrar menos
Sem etiquetas

Contexto

A-7 Find cheap airline tickets Given that you have this data that shows 10 airline companies and their corresponding average ticket prices. let airlinePrices = [   {airlinesName: 'Lufthansa', avgPriceTicket: 85.6},   {airlinesName: 'Aegean', avgPriceTicket: 65.8},   {airlinesName: 'KLM', avgPriceTicket: 102.82},   {airlinesName: 'British Airways', avgPriceTicket: 114.9},   {airlinesName: 'Iberia', avgPriceTicket: 77.2},   {airlinesName: 'TAP Portugal', avgPriceTicket: 58.9},   {airlinesName: 'Alitalia', avgPriceTicket: 84.2},   {airlinesName: 'Air France', avgPriceTicket: 105.6},   {airlinesName: 'Singapore Airlines', avgPriceTicket: 119.2},   {airlinesName: 'Emirates', avgPriceTicket: 135.4}, ] Try to create a function that accepts a collection of data (in this case this array) and returns only the names of every airline company whose average ticket costs less than 100 Euro. Bonus: Try to use no if-statements etc. Make this as compact as possible. Which array method should be useful here?
Mostrar menos
Sem etiquetas

Contexto

Nesting arrays As you probably have noticed until now arrays can store multiple values in one place under one variable. Later we can grab these elements by specifying the index of the array to return a specific element from the given position.  Arrays can store multiple values of various data types like strings, numbers, boolean and of course other arrays. Nested arrays are possible and elements can be accessed as the example indicates above by implementing double square brackets. The first square brackets find the element inside the outer array, if the element at the given position is also an array that holds multiple values, then specific values of this nested arrays can be accessed by simply typing a second pair of square brackets, directly after the first one!  On the example above, if we want to compare the two test results between two students, we need to first access them. As we can see the first result lies, at position 0 of the outer array, which happens to be an array that holds a name and the score. Then the score lies at the second position and can be accessed by index 1. The same functionality can be applied in order to grab  the next element score with the correct indexes ([1][1]).
Mostrar menos
Sem etiquetas

Contexto

A-8 Groceries Nesting exercise Your wife / your husband has left urgently for work this morning and has left you the list for the grocery items that you should pick from the supermarket for the week. Because he/she was in a rush meshed it up and you ended up with 2 lists.  The first list contains the names of the groceries. And the second one the amount of every corresponding items you should buy. The groceries list is comprised of 5 items. chocolate, bananas, rice, beers, deodorant. The amount for each is: 5, 5, 2, 6, 1. Store these lists in 2 different arrays. Then find a way to create a pair for every index (ex. ['chocolate', 5] and store this into an empty array. The final result should be: [['chocolate', 5], ['bananas', 5], ['rice', 2], ['beers', 6], ['deodorant', 1]]. In the end find a way to print 5 times a message to the console that says: Please buy 5x chocolate. Please buy 5x bananas. Please buy 2x rice. Please buy 6x beers. Please buy 1x dedorant.
Mostrar menos
Sem etiquetas

Contexto

The reduce function The reduce function is another high-order array method that accepts two parameters. The purpose of this function is to convert or reduce an array into a single value.  For example when you want to grab the sum of the numbers an array holds. As the picture above shows, you need to specify two parameters, The first is the function that is going to make the reduce, and the second one is the starting point where the reduce is going to use as a point of begin. Then the callback function accepts two arguments, the first argument (in this case a) represents the summary (at the beginning is 0, then it is updated with the value of each return statement after every iteration). The second argument represents each one of the array's entries (or values etc). To understand this better, let's try to take a look at every iteration of this reduce function and see how it works.    First iteration: a = 0; b = 0. So the result of (a + b) = 0, that means that next iteration a = 0. Second iteration: a = 0; b = 1.  So a = 1 for the next iteration. Third iteration: a = 1; b = 2; So a = 3 for the next iteration. Fourth iteration: a = 3; b = 5; So a = 8 now. Fifth iteration: a = 8; b = 7; So a = 15 now. Last iteration a = 15, b = 3. So the result that comes after the reduce is 18.   For Official documentation check it out here!
Mostrar menos
Sem etiquetas

Contexto

A-9 Assembling a string with reduce Given that you have an array of words together like that: let myQuote = ['it', 'is', 'Friday', 'and', 'i', 'am', 'already', 'exhausted', 'to', 'think', 'of', 'a', 'better', 'quote']; Try to create a single unified string but by using the array's reduce function. Try to use all array's elements to assemble the string from the beginning.
Mostrar menos
Sem etiquetas

Contexto

A-10 Aggregate Basket Imagine that you are working as a salesman for a shop that sells some goods. For the sake of the example let's assume that you sell 4 kinds. Smartphones, laptops, smartwatches and air-coolers.  Anytime you sell something, you save it by writing down the good you sold ('smartwatch') for example. At the end of the day you take a look at your sales and you end up with something like this. let sales = [   'smartphone',   'smartphone',   'laptop',   'smartphone',   'laptop',   'air_cooler',   'smartphone',   'smartphone',   'laptop',   'smartphone',   'smart_watch' ]; Create a function that aggregates this array and returns an object with the product names as keys, and how many of them were sold as values. Your final result should be: {smartphone: 6, laptop: 3, air_cooler: 1, smartwatch: 1} You can check always if an object already contains a property from before with the Object.hasOwnProperty('property') that returns a boolean value (equivalent to the includes for arrays). Maybe you want to find out more here before proceeding. An alternative and more elegant solution may include an array's reduce function. You may want to think about how this is going to be done.
Mostrar menos