JavaScript Array Mastery: Tips, Tricks & Best Practices

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] thank you arrays are incredibly useful because they are a special type of data structure that allows us to store and manipulate a collection of values within a single object but with their specialness also comes quite a bit of confusion because after all they are very different than other types of data structures and that's okay we've all been there and now I'm here to help hi I am Jeremy McPeak with envato touch plus and I invite you to spend the next hour with me as we walk through some of the key features Concepts and abilities of JavaScript arrays in this course you'll learn the primary mechanisms that we use to iterate and process arrays how to sort them search them copy them and manipulate them now before we begin be sure to like And subscribe the envato touch plus Channel and now let's get started we are going to begin by looking at some of the basics now chances are you already know this stuff and feel free to skip over the content that you feel like you need to skip over but if you feel like you need this little refresher then great if you are brand new to arrays this is going to be a very fast crash course and really I would recommend you look at some of our other JavaScript content we have many tutorials and courses that would actually serve you a lot better because it would go more in depth at a much slower Pace however if you want to stick around then great it's nice to have you so let's begin by creating an array of numbers now we can do that by calling the array Constructor but you will typically never see that because just about everyone creates an array by using array literal notation which is just a pair of square brackets and whenever you create an array it is empty by default but you can pre-populate that with any values that you might already know so this is going to be an array of numbers let's start with one two four and eight so we now have an array called numbers it has four items or four elements and we can access those Elements by using the index notation indexes are just the positions of those values so the index begins at zero so at index 0 is the value of one at index one it's two and index two it's four at index 3 it's 8. so if we wanted to access the value at index of 3 to get the value of 8 then we would use index notation which is simply just the name of the array followed by a pair of square brackets and inside of the square brackets we have the index so let's write this out to the console and we can see that over on the right hand side we will see the value of 8. there it is so that's all well and good but let's say that we need to add some more values to this array well we can do so in several different ways the first is to use index notation so the next index would be four and we can simply assign our numeric value at the index of 4. so this is putting the value of 16 at the end of the array and if we write this out to the console we will see that is indeed what happens so the first version of the numbers array has four elements after we add the value of 16 we now have five elements but a lot of times you don't know how many elements there are in the array and you just want to add an item at the end of that array well we have a method that easily does that it is called push the idea is that you are pushing a value into the array so here we're going to push the value of 32 which is going to add that value at the end of the array so if we take a look at this in the browser once again we see the first two versions of the array but then we have the array that now has six elements and we can see that the value of 32 is at the end but sometimes we want to insert a value at the beginning of the array and we can do that using the unshift method we simply pass in the value that we want which in this case is going to be the value of 0 and that is going to insert that value at the beginning so let's once again write out our numbers array to the console and we will see that it changed we now have seven items within this array the first item is 0 then 1 2 4 8 16 and 32. now if we can add items to an array then it goes without saying that we can remove items as well and one of the methods that we can use is called pop so this is essentially the opposite of push push is we pushed a value into the array pop is we are popping a value off and in fact it's going to pop off the last element in the array so we can store this within a variable I'm going to call it simply last number and we will call numbers dot pop that's going to pop off that value which is the value of 32. so let's do this we are going to write out the numbers array then we are going to write out the last number variable so that we can see that that value is 32. so let's refresh the browser we can now see that our array does not have the value of 32 because we popped it off and we stored that inside of the last number variable so there we go so push allows us to push a value into the array at the end of the array pop lets us pop that value off and if we can use the unshift method to insert a value at the beginning of the array well then we have a method called shift which does the opposite it takes the first element in the array and removes it from the array but we can also store this in a variable so let's once again write out our numbers array to the console let's also write out the value of first numbers so that we can see what that is let's refresh the browser and there it is we have our array with five elements now because we removed the value of zero we stored that within the first number variable and then we can use that value whenever we need to now about the only way that we can remove an item by its index is by using the splice method for right now we just want to remove a single item so let's say that we want to remove the element at index 4 which is the value of 16. that's what we added using the index notation so the splice method actually lets you remove one or multiple elements within the array but since we only want to remove one we need to specify that the first thing that we need to pass to the splice method is the index of where we want to start removing and then we need to specify how many items do we want to remove in this case it's just one we want to remove that one value of 16. so after we call splice we can write out our numbers array to the console and then finally we will be back to our original version where we have four elements one two four and eight well in the next lesson we will take a look at some of the basic Loops so that we can iterate and process arrays in the previous lesson we looked at the very basics of arrays we talked about how to create them add items to them and remove items from them in this lesson we are going to continue looking at the basic 6 and we will look at the two most common Loops the for Loop and the while loop and what I want to do is create a shopping list as you can see over on the right hand side of the screen there is already some text for a shopping list and if we look at this HTML we have a UL element that has an ID of list and basically I want to take the items inside of the array that we are going to create and I want to create Li elements so let's say that we want to make breakfast so we need to get some milk we need some butter and some bread and some eggs and all of that stuff so the end result is going to be an unordered list that has Li elements for of course the things that we need to buy but of course we're going to generate those using JavaScript so let's start by creating this list array we want some milk we also need some eggs this let's get some butter for the bread that we are going to make for toast and then of course we need some bacon and for each one of these strings we want to create an Li element so that we can display that in our list and we do that by using a loop now this is one of the reasons why we have arrays it is a collection of things that we can work with very easily we can process them using the same code and that's what a loop does it executes the same code for every item inside of an array and probably the most common Loop is the for Loop which has four parts to it the first is the initialization the second is the condition the third is the increment and then the fourth is the code that's actually going to execute so the initialization is typically used for initializing a counter variable something that we can use to keep track of the index of the item that we are currently working with so let's do that we'll create a variable called index and we want to start the loop at the very beginning of our array so index is going to be zero now if you're looking at other people's code they might use the variable name of I that's very common I use I I because if I need to search for my counter variable well there's not many words that have two consecutive I's the same can't be said for just I because well list has an I milk has an i and there's a lot of eyes that you find in your code so I use II but let's use index because that is exactly what we're going to be doing we're going to keep track of the index now the second part this condition this determines if the loop executes or if it exits so if it's true the loop executes never use true here but if it's false then of course the loop will exit so we want to execute our Loop for every element within our list array so that means index needs to start at zero for milk we need to change index to 1 so that we can work with eggs then the index needs to be 2 to work with better and so on and so forth but we only want to work with the amount of items inside of this list so one thing we could do is say that as long as index is less than 5 because we have five elements and remember that since we start the index at zero by the time we get to bacon that is index four so if we get to index five then we want to exit the loop however we don't want to hard code our limit here because if we ever decide to add some sausage because well if you're going to have bacon you might as well have sausage well then we also have to come to the loop and we have to change our limit here so instead said what we can do is use the length property on our array that's going to return the length which is as it happens the limit of our array and anytime we add a new element to the array well let's get some juice then that length is going to change and then finally the increment we want to increment our index every time the loop executes that's how we know if our index is less than the length of our array all right so we simply want to generate some HTML so let's do this let's create a variable called HTML we'll start it off as an empty string and then what we will do is get our unordered list elements I believe the ID was simply list and we will set the inner HTML equal to that HTML so that inside of the for Loop all we need to do is just add a new Li element to our HTML string and since we have just simple strings we can say list and then use index notation to get the item at that given index and there we go so if we save this let's go to the browser and refresh there we have our list of things perfect but most of the time we aren't working with simple values we are working with more complex values like objects so I'm going to paste in some objects these objects have have three properties the first is the text that's what we want to display in the browser the second is the cost because it would be nice to actually show the cost of the item so that if we have a budget then we can at least say oh okay this list is going to be you know roughly 30 something dollars and then later we will talk about this need property Let's ignore that for now so let's go to our HTML let's add a span elements to this H2 so that we can output the cost here and let's just give this an idea of cost so that's going to work fine let's go ahead and set up that so that we output that value and we will put a dollar sign before it uh let's have a running total we'll just call it total why not and so let's create that total variable we will initialize it at zero and so now if we refresh the browser we should see Zero but notice now that we see object object well that makes perfect sense because we are no longer working with just simple strings we now have objects so whenever we want to Output the text we have to use the text property so let's refresh and there we go so we can make our lives a little bit easier inside of the loop by creating a variable we'll just call it item and we will get the element at the given index and then we can just use this item variable to reference the object that we are currently working with so this makes it a little bit easier to process all of this information so now we want to process the cost and we will simply take each item's cost and add that to our running total which that variable name is called total so with that in place we can refresh and voila we have our shopping list we expect it to be thirty four dollars but well money's tight right now so let's say that we have a budget of thirty dollars well okay and that's where this need property can come into play yes it would be nice to have milk but we don't really need that for our breakfast so we need to include that as we are processing the array inside of the for Loop so let's just add an if statement if we need that item then we will output that item to our list and we will calculate the total there otherwise we just ignore that and whenever we run this in the browser we are going to see our total changes we are now under budget we're at 25 bucks which that's good saving money is always great and we have our eggs bread and bacon so there we go that's the for Loop now another common Loop is the while loop so let's take a look at that we will essentially do the same thing such as outputting information we will also take into account all of the other information about our shopping list but we will use the while loop now the while loop has just two parts to it it has the condition which once again it will determine whether or not the loop is going to execute and then the second part is the code that will execute so this particular Loop is very easy to get into an infinite Loop if you have a condition that is always true you are going to have a rough time but let's essentially do the same thing that we did for the for Loop but we will use the while loop so that as long as we have an item to work with then we can work with that item inside of our Loop so let's copy and paste our code at least for checking if we need that item and then processing that item but that in and of itself isn't going to work because as it is right now we haven't done anything with this item variable it doesn't even exist so let's start by creating that item variable and we will initialize that as the first item within our list but be very very very careful here because as it is right now our code doesn't change item one bit and actually this code won't work because we don't have that index variable but that's easy enough to do so we initialize index as zero we get the first item in the list we use that as the condition for the while loop but since we never change the value of item we are in an infinite Loop we could go over to the browser and refresh this but no I'm not going to because we wouldn't really see anything because the loop would never exit and we would never execute this code here so instead what we can do inside of this while loop is set a new value for item to where we will once again use index notation but we will increment index here so the concept is very similar to what we did in the for loop it's just organized in a slightly different way all of our initialization stuff is done outside of the loop we rely upon the condition to determine whether or not the loop will execute we do the loop but then we need to change whatever values we've used inside of the condition otherwise we would end up with an infinite Loop but if we save this we go to the browser and refresh we can see that we have the same exact result and if we decide that's hey money is great we don't need to worry about our budgets we can comment out the code for determining if we need that item and if we refresh we have a bug because we initialize the item as the first element in the array now what we could do is organize this a little bit differently so that instead of just using item for our condition we could use the assignment of the item and then whenever we create the item variable we just won't initialize it that gives us a little bit cleaner code and so now if we take a look at the browser we can see we get the correct results and once again if we needed to factor in our budget we could just uncomment that code refresh and we have our condensed shopping list let's continue this discussion on iterating arrays because while the for and while Loops are useful a lot of times we just want to iterate the array so that we can work with the individual elements we don't necessarily care about the index or anything like that and we certainly don't want to go through the rigmaro of setting up a traditional for Loop or priming up a while loop so there are essentially two different ways of just iterating over an array the first uses the for each method this takes a functional approach because you pass a callback function to the for each method and this callback will execute for every element in the array so this callback function has three parameters the first is the most important it's the item or the element that you want to work with inside of the array the second parameter is the index so if you need the index then that is a perfect way of getting that and then finally the third is the array itself that you are working with now of course you can use all of those that you want but typically you just want the item so I'm going to make this a little more concise so that's it's a little bit easier to read so I'm going to use an arrow function and so just this alone alone we now have access to the item that we want to work with we don't have to create that variable or anything like that don't have to Prime anything it's just given to us by default so we can take the code from our while loop and we can just paste that inside of the Callback function for our for each and whenever we run this in the browser we are going to see the same exact results perfect that's what we want most of the time this is what we want to do just iterate over the array however once again if you need access to the index just get the index as the second parameter for your callback function now we can make this a little easier to read by destructuring this item parameter we need the text property the cost and the need property and then inside of our callback function we can just refer to those individual values we don't have to have item dot in front of them and everything is going to work just as it did before so great perfect awesome however if you don't want to use the for each method because it does require a little bit of different thinking because it is functional programming we do have another version of the for loop it's called the for of Loop and it looks like this we start with four but instead of having an initialization a condition and all of that stuff we create the variable that we want to work with the individual item here of and then the name of our array list so for each item of our list we want to essentially do the same thing that we did with the for each Loop but you know we can destructure this as well so if we just need the text and the cost that's great we can do that but we also need need and then this gives us a quick and easy way of just iterating over that array as well so let's comment out our four each and let's refresh and we get the same exact result now if for some reason we are using the four of Loop and we need to access the index we have to do a little bit more work because it's not going to give us the index by default so instead what we can do is call the entries method on the list now this is going to return an iterator an iterator is a special kind of object that produces a sequence of values in this particular case the sequence of values is a set of key value pairs the keys in this particular case are the indexes and then the values are the individual items or the individual elements that we want to work with and these key value pairs are actually inside of another array the first element in this key value pair array is the index the second is the value so it's a little more confusing and really if you need access to the index I recommend using something other than the four of loop because the for each Loop is perfect for that it gives it to you out of the box by passing it as an argument for your callback function or use the traditional for Loop but still we've started down this path let's finish it so we could do this we can destructure this so that we have the index and then we have the item but also we want to destructure the item so we will do that as well so now we have access to the index if we need that so let's output the index of each one of these items whenever we output the text so that in the browser we can refresh the page we can see the indexes for those items in the list again while this works if you need the index use something other than a four of just because it takes everyone's brains a little bit longer to decipher this code to understand what's going on and you are typing a lot more than you would need for the for each method so keep it simple with the four of in fact I'm going to back out those changes so that we don't have to see them in the next lesson we will talk about sorting arrays sometimes you just want to sort an array especially if you plan on displaying the contents of that array to the user because we humans are very simple we like things in order so JavaScript makes it very easy to sort in ascending order all we need to do is call the sort method and that's it now this is a destructive method this changes the array so this doesn't create a copy that is sorted this actually changes the order of the elements so as I've defined this list array in eggs buttermilk bread and bacon whenever we call the sort method we are going to see that it is sorted in a sitting order big bacon bread butter eggs and milk now JavaScript does not have a method for sorting and descending order however we can get a descending ordered array by calling sort and then simply reversing it and in the browser we can see that it is indeed in descending order now the only reason why this works is because the reverse method it doesn't do any sorting it just simply reverses the array so what is the first element becomes the last element what was the last element becomes the first element so if we take a look at this in the browser you know we can see that the original order is eggs butter milk bread bacon in the Reversed order it is bacon bread milk butter and eggs so of course if you want descending order then just sort it and then reverse it but that is a little inefficient from an execution standpoint it would be better to just sort it in descending order and we can do that because we can pass a callback function to the sort method now this callback function is a comparison function it is going to accept two elements from the array and we are supposed to compare them we need to return one of three values we need to return 0 which typically means that a is equal to B which also means that there is no change because if a and b are equal then there's no reason to change their order they're equal so there's no change if you return 0. now you can return a negative value but we typically just return negative one this typically means that a should be sorted before B and then the only other value is a positive value which once again is just usually one and that means that b is sorted before a so those are the values that we need to return so if we want to sort our array in descending order it would look something like this we will start off with our easiest comparison because if it's equal then we just return 0. but if a is greater than b well that means that we want a to come before B because we are sorting in descending order which means that we need to return one there otherwise we just return negative one because that's the only other thing that we can return so with this in place we should be able to refresh in the browser and no that is sorted wrong oh because my logic is wrong if a a is greater than b then we want a to come before B which means that we need to return negative one that was my fault so there we go now whenever we refresh we see that it is in descending order so perfect of course if we wanted it in ascending order well there would be no reason to pass a callback function unless if you were working with something like an array of objects so let's take a look at that because in most cases we're working with objects as opposed to just simple values so we have a second list I'm going to just call it list two this is our breakfast stuff and let's say that we want to first of all sort by the text property okay we can do that very easily by just using the text property inside of our comparison so we're going to compare a text to B text and of course we need to change which array array that we use here but other than that that should work although whenever we call for each let's do this let's extract out the text so that we can see that within the browser so once again we see our sorted array in descending order but let's say this let's sort our items by cost so that instead of text we do so by cost so that should be easy enough to do but let's make this in ascending order so this means that if a is greater than b then we need to return one otherwise we return a negative one but we also need to display the cost so that we can easily see if it is correct or not so let's add cost to our output and we should see our array sorted in ascending order based upon cost and we do and of course if we wanted this in descending order we could just flip this comparison and that will change the sort order to be in descending order based upon the cost so if your array is simple values then using the sort method can be very simple but of course the more complex the data is the more complex your sort callback function is going to be but of course the fact that you can provide a callback function means that you can sort your data however you need over the next couple of lessons we will talk about searching arrays because you know remember an array is just a collection of things and sometimes we want to search an array for an index of an item or we need to find an item based upon a certain criteria or sometimes we just need to know if an item exists within an array so in this lesson we will talk about finding the index of an item within the array and there's really three methods that we can use to do that the first is called index of and as its name implies it is going to return turn the index of an item that you provide for example we have a list of just simple values and let's say that we want to get the index of the item that is butter so let's write this out to the console we will pass butter to the index of method and it will return let's see that is index two so over in the console we should see the value of 2. and we do if we change it to Red then we should have the index of four because bread is at the index of four so it's a very easy and straightforward method but what happens if you try to find an item that does not exist within the array like sausage well that returns negative one which makes perfect sense really because you know an index can be zero or a positive integer so really the only thing that can denote an invalid item or at least an item that does not exist within the array would have to be a negative value so negative 1 is what index of will return but let's look at this notice that we have bacon twice inside of this array we have it at index of zero and then index of what is that five yes I believe five so let's see what happens if we find the index of bacon well in the console we see the value of zero which also makes perfect sense because the index of method is going to search an array starting at index zero and it's going to search the array until it finds a match or until it gets to the end of the array so in our particular case we want to find the index of bacon well it found bacon on the very first element so it stopped searching because it found a match so we get the value of zero but what if we want to find this second occurrence of bacon well we can pass in a second argument to the index of method which is the starting index of where we want to start searching so if we start searching at index one well then the value that index of returns is going to change because it's going to start searching at eggs and then it's going to search through to the end of the array so we get the value of 5. now an alternative solution would be to use the last index of method which almost works exactly the same except that it starts searching at the end of the array and it searches towards the beginning so if we use last index of and pass in bacon since it starts searching at the end we are going to see the same value 5. because that's where it started searching so index of and last index of are very very easy methods it will return negative one if it cannot find the item that you were searching for otherwise it Returns the index of that item now one thing of note is that index of and last index of work best with very simple values for example we have strings if you have an array of numbers index of and less index of is going to work very well but what if you have a more complex value like an object so I'm going to paste in an object we don't necessarily need the need property so let's get rid of that and let's say that we want to find the index of this particular object that has a text of red and a cost of three well we can try to use the index of method however here's the thing an object is a reference value it is a reference in memory so if we take this object and we pass that same object well it's not really the same object it looks like the same object we are going to see negative 1 in the console and the reason is because the that according to JavaScript these are two completely separate objects what we have inside of the list array and what we pass to the index of method looks exactly the same but they are two different references of memory so instead what we can use is a method called find index which gives us the ability to pass in a callback function and it is going to use that function to try to find whatever it is we specify so we want to find the object that has the text of bread so that could look like this we would have a callback function to where we work with the individual item and we simply want to find the item that has bread for its text the return value of this callback function needs to be a Boolean value if it returns true then the find index method has found the item that we are searching for if it's false then it's not is going to continue searching through the array so if we take take a look at this in the browser it changes now we can see that our object that has the text of red is at index six and of course we could simplify this using an arrow function so let's do that so when it comes to finding the index we essentially have three different methods that we can use the index of and the last index of methods are useful for simple values the find index method is useful for objects or reference value in the next lesson we are going to talk about the find method which is somewhat similar to the find index method except that it allows us to search an array for an actual item so that we can retrieve that item sometimes we just need to find an element in the array we don't need the index or anything like that we just need to find an element so that we can work with that element and the arrays find method does just that now this is a a lot like the find index method that we looked at in the previous lesson in that we provide a callback function that is going to test each element in the array and this function needs to return a Boolean value if it's true then well we've found that item and so the find method is going to return that item to us if not then it's going to keep testing all of the elements until it reaches the end at which point we don't find anything so here we have our list of things these are more complex objects which the find method is perfect for because our little testing function gives us the ability to test whatever we need to test so let's say that we want to find the item that has the text of eggs well we can do that our testing function is very simple in that case because all we need to do is check the text property if it's eggs then great we then have that item that we can work with so that's in the console we will see that object we successfully retrieved that object we can see the cost if we need it and of course the text what happens though if we don't find a match like for example if we try to find an element that has a text of sausage well that object of course does not exist so undefined is returned to our variable which which makes sense because we aren't dealing with indexes or anything like that so getting a value of negative one like we did in the previous lesson doesn't make much sense we didn't find anything we don't have a value to work with so therefore it is undefined but let's say that we need something a little more open-ended we don't necessarily want to look for an item that has an exact text let's just say that we want the first item that has a cost less than five well our function would look something like this to where the cost would be less than five and once again it's going to search the array be starting at the beginning and it's going to test each one of those elements until it finds a match at which point it's going to return that so according to our costs that should be the item of milk so let's run this in the browser and sure enough that's what we get that is the first object that had a cost less than five now one of the great things about the find method is that while it seems very suited just for objects that's not necessarily the case we can use it for any kind of value so for example I'm going to paste in an array of numbers 5 9 23. if you notice pretty much all of them are odd numbers except for one 54. so let's say that we want to find the first number in our our numbers array that is even well we can do that very easily by using the mod operator so if the value mod 2 is equal to 0 then we have an even number so if we output this variable to the console we should see the value of 54 because that is the first and really it's the only value inside of our numbers array that is even so it doesn't matter what type of data that you're working with the find method is very useful if you need to find an element based upon certain criteria we've talked about finding an index of an element we've also talked about finding elements themselves but sometimes you just need to know if an element exists inside of an array and JavaScript gives us several methods that we can use to do just that all of these methods return a Boolean value true if the item exists false if it doesn't and we will begin with the most simple method it's called includes and I say that it is the most simple because you would typically use this with the most simple kinds of values like strings or numeric values so in that sense it's a lot like the index of and last index of methods however there are some times when you would want to use it with a reference value but those particular times are really up to you if it fits your use case so here I am calling includes on our numbers array we're going to see if the value of 23 can be found and of course it is because it is defined as the value-add index 2. but let's see if the value of 24 is there and of course that is not so it returns false so it's a pretty simple method now if you need a little more flexibility then we can use a method called sum the idea being that we are going to check if at least some of the elements in the array meet a certain criteria so here we're going to use our list of objects and we're going to call sum and let's say that we want to see if there are some items within this list that are needed you know so we have that need property so we would pass in a callback function that would test each element in the array well actually it doesn't test each element if it finds is an element that passes our test then it is going to just automatically return true because in that particular case sum of the elements do meet that criteria so here we will check if an item is needed and of course we are going to see the value of true because we do have some items that are needed but let's do this let's set all of the items as false just so that we can see that whenever we refresh the page we can see that the returned value of the sum method is false but even if just one is true then the return value is going to be true so we can provide a callback function that will test to see if an item matches that criteria and then the third method is somewhat similar except that it will return true or false based upon if every element in the array meets a certain criteria so let's go back to our numbers and let's say that we want to see if every number in this array is an odd number to do that we simply call the every method once again again we pass in a callback function that will test the elements in this array and we can determine if a number is odd using the mod operator if it is not zero I guess that's what we ought to check for then that would mean that the number is odd so let's refresh the page we're going to see that it is false because we do have one even item but let's change that to an odd numeric value let's refresh the page and we see that it flips to true because every value inside of the numbers array is odd and so by using the includes sum and every methods you can determine if an element exists in an array eventually you will want to merge multiple arrays into a single array and JavaScript gives us the tools that we need to concatenate or merge multiple arrays now I use that term concatenate specifically because we have a method so simply called concat short for concatenation and it does what you would think it does it concatenates multiple arrays into a single array now this does not modify any existing array this creates a brand new array that contains the original array that we start with in this case I have two arrays one called odd one called even so I'm going to start with the odd array and we are going to concatenate the even array with odd this will give us a new array which I am storing in the numbers variable and we can write that out to the console in fact let's do this let's write out the odd even and the numbers array just so that we can see that the original arrays are still intact without any modification and of course our new array contains all of those values so the first two arrays are of course the odd and even everything is the same there but let's take a look at our new array the numbers array we have all of those values but also notice that they are in the same exact order that they appeared in their original arrays so we started with the odd array so the first few values are from the odd array we concatenate the even array and those appear afterwards and they are in the same order but let's say that we have a third array that we want to concatenate with those and let's just call this letters so we will have a few string values to represent individual letters and then we will pass letters as a second argument to the concat method and that's all that we need to do it is going to concatenate all of those arrays into a single array and just like before all of the values are going to be in the order that they appear appeared in their original arrays so once again we have the odd we have the even and now we have the letters array but now we can take a look at well it's no longer numbers is it but we can see that once again we have the values from the odd array we then have the values from the even array and then we have the values from the letters array so it's a pretty simple thing to do just to call the concat method now we can also merge multiple arrays by using the spread operator so let's do the same thing except let's call this alpha numeric because that is exactly what it is and all we have to do is just create a new array and we will spread out the odd the even and the letters array so we essentially end up with the same exact type of array but now it's a bit more declarative than using the concat method and if we take a look at the output of course the first three arrays are the same we haven't changed those but are alphanumeric array has the same values in the same order that the concat method gave us so when you need to merge multiple arrays you have two options you can call the concat method or you can use the spread operator of course there will come a time when you want to copy an array and JavaScript gives us the slice method to do just that we simply call the slice method on whatever array that we want to copy and that is going to create a copy now the name slice is a missed no more to me because it makes me think that I'm slicing out things into another array and that's not the case it doesn't modify the existing array at all it just copies it so we're going to start by this we're going to copy the entire array and let's first of all write out the copied array to the console we are going to see we have those five items but let's do this now let's see if the copy array is the same array object as list you know kind of like we would have two variables that reference the same thing well I can go ahead and tell you that that is not the case because whenever you call the slice method it is going to create a brand new array it's just going to contain the same things and that there is key because since we are dealing with objects these are reference values the slice method doesn't create a copy of these objects since these are references the references are copied to the new array so what we end up with are two arrays that contain the same references so you can get yourself into trouble if you copy an array and you think that you are working with different objects now values on the other hand you know simple values like strings numbers Boolean you don't have to worry about that because those are values they aren't references if you're dealing with objects then you have to worry about it now let's say that we want a shorter copy we don't want to copy the entire list array so that's where the arguments that we pass to the slice method come into play the first argument is the index of where we want to start the copy so let's say that we want to copy bacon eggs and butter so our copy will begin at bacon and and we want to copy the next three items so we pass in the number of items that we want to copy not the ending index of what we want to copy to this is the number of elements that we want to copy so in this particular case this is going to give us a new array that contains just bacon eggs and butter so let's refresh we see we have that new array with those three items and that's it the slice method is very straightforward the key thing to remember is that it doesn't change the existing array but if you do copy an array of objects just know that the objects are shared between the two arrays JavaScript has the ability to transform an array into a string and I use that term transform very Loosely because the methods that we talk about typically don't change the array itself it leaves the array alone instead it simply returns a new value so like the slice method that we talked about in the previous lesson it did not change the existing array it just created a new array well the method that we will talk about in this lesson is called join and it will join the individual elements of an array into a single string so if we don't pass anything to the join method it is going to separate each one of the elements with a comma so let's see what this looks like we will retrieve the elements with the ID of list and then let's set the inner HTML to our new HTML so this HTML variable is going to contain the text of bacon eggs butter milk and bread and of course everything is separated with a comma but we can change that by passing anything to the join method I say anything whatever we pass through the join method is what is going to separate the individual elements so if we pass in an empty string well then we're going to get a string of all of those words just combined together that's not very useful at least in our case I could see where that would be useful in other cases but that's not very readable to the user now of course a comma operated list is somewhat readable but let's do this let's separate each element with a breaking line so that then every element is on its own line that's much easier to read and that is essentially it transforming an array into a string is as easy as calling the join method all you have to do is specify whatever you want to separate the elements and that's it it really doesn't get any easier than that transforming an array into another array is a very very common thing especially if you start using some very popular UI Frameworks like react now I use that term transform and that's really not the right term to use here because it makes you think that we are changing or manipulating an existing array and we aren't we are creating a new array that contains trans formed data and we do this by using a method called map so here's what we want to do in the past when we talked about the loops such as the four of loop the while loop for Loop and the for each method we created Li elements using our breakfast food information and we displayed those Li elements in the browser we're going to do the same thing but now we are going to use the map method which is arguably the correct way of going about doing this so we will call map and we need to pass a callback function that is going to execute on each item within our list and it is going to Output the LI element that contains all of the information that we need so we need our function that will work with the individual item and let's go ahead and destructure our items so that we have access to text cost and the need properties and to start with let's just return An Li element that has the text and we will go from there so what the map method is going to do is execute this callback function on every element and it's going to create a new array that will contain this transformed data so let's just write this out to the console so that you can see what the end result is so let's do that let's open up the console in the browser let's refresh and here we have an array of five elements but you can see that the text is here these are Li elements that contain bacon eggs buttermilk and bread so we now have a transformed array that has the data that we need to display within the browser however we need to convert this array of strings into a single string so that we can easily add that to our list within the browser well we already know how to do that because in the previous lesson we talked about the join method that's how we converted an array into a string so we can take our list elements and we can join them together with an empty string and we are going to end up with our list of things bacon eggs buttermilk and bread perfect so let's include the cost so that we can see that information and whenever we view this in the browser we see the cost as well so now let's incorporate the need property and let's say that if an item is needed then we will simply return that Li element but if it's not then we will return just an empty string because remember that we need to return a value here this callback function is responsible for transforming each individual element into whatever it is that we want so if the item is needed we want the LI element if it's not needed we don't need to display that in the list so we will just have an empty string because ultimately it doesn't matter because once we join the elements together and set the inner HTML all of those empty spaces aren't going to be rendered within the browser so let's refresh now and we can see that we have bacon eggs and bread because those are the only items that we actually need but we can do this a different way by using another method called filter which we will look at in the next lesson we used the map method to transform our array of objects into an array of strings that contains HTML and if the item was needed then of course we have the HTML to display that item in the browser if it's not needed we just have an empty string and while this particular approach works I don't like it because when it comes to the map method I want to work with only the elements that I need to work with so for example the map method only needs to work with the elements that are needed so that it would be great if we could just eliminate the use of that need property so that our method looks like this and in fact we could even break this down even further by using the arrow function syntax because I like nice neat concise code and thankfully we have the ability to filter and an array the method is called filter now once again I feel like I need to stress this that the methods that we are talking about do not change our existing array it simply creates a new array that contains whatever it is that we are doing so like the map method created a new array with our HTML elements well we have a method called filter which will filter an array but again it doesn't change our existing array it creates a new array that contains the filtered elements and this accepts a callback function that will test each element in the array and if the test is true that element will be in the new filtered array if it's false then it will be left out so we want only the items that are needed so let's do this with an arrow function because this is going to be very simple if the item is is needed well then we want to display that so right here we have filtered our array of objects into another array that contains only the items that are needed so that whenever we map them we are working only with those three elements so in the browser whenever we refresh we see the same exact results that's great well let's change this up a little bit let's say that we want the items that we need and we want only the items that cost less than twelve dollars so that's going to filter this down even more so whenever we refresh this in the browser we now see eggs and bread and if we take a look at our data yes that is indeed the case our eggs are ten dollars our bread is three dollars everything else is either too expensive or it is not needed so by combining the use of multiple methods together we typically call this chaining method we can do some very powerful stuff thank you so much for watching this course it is my hope that by now you have a thorough understanding of how to iterate sort search copy and manipulate arrays they play a key part in data manipulation and processing not only can we iterate arrays to transform and aggregate data but we can sort them in whatever order we need to display that data as we see fit and because arrays are Dynamic we can easily add remove and modify elements allowing for convenient manipulation and updating of data arrays are a crucial part of not just JavaScript development but development in general they play a major role in many applications and systems again thank you so much for watching this course please feel free to contact me through Twitter or the touch plus forums if you have any questions if you enjoyed this content please like And subscribe we have a lot more where this came from once again and I am Jeremy mcpeek with envato touch plus thanks again and I will see you next time
Info
Channel: Envato Tuts+
Views: 13,389
Rating: undefined out of 5
Keywords: javascript arrays, arrays in javascript, javascript array methods, javascript course, learn javascript, javascript array functions, javascript array tutorial, javascript, javascript arrays tutorial, javascript array, javascript array methods tutorial, javascript higher order array methods, javascript tutorial, javascript programming, javsacript array functions, must know array methods, array map explained, arrays explained
Id: cDCzz8vJf3Y
Channel Id: undefined
Length: 62min 48sec (3768 seconds)
Published: Wed May 31 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.