The array methods in this article are next level (a.k.a. level 2), in my opinion. Learn these array methods after Level 1 Array Methods. Remember, I am trying to make this easy to understand without the extra fluff. For more in-depth array method explanations, go to the Mozilla Developer Network website.
This is part 2 of my “Array Series.” If you missed part 1 then go here: Level 1 Array Methods.
Add Item at Beginning of Array
Unshift adds the item in parenthesis to the beginning of the array and returns the number of items in the array. The array becomes one item larger and moves existing items up one index.
Use case: When you are taking a coding challenge and they ask you to add an item to the beginning of the array.
Los Angeles went from an index of 0 to an index of 1 when you add an item to the array using
Remove Item at Beginning of Array
Shift removes the first item in the array and returns it.
Use case: When you are taking a coding challenge and they ask you to remove an item from the beginning of the array.
Join Items in Array into One String
Join concatenates all the items in the array into a string. (Concatenate is another way to say
Each item from the array will be separated by what you put in the parenthesis. Commas will be used if you leave join parenthesis blank.
Use case: When you receive data that is separated in an array, but you need it in one string.
Sort an Array
Sort reorders items in the array into alphabetical order, then returns the array in its new order. The array items are sorted as strings (UTF-16).
Use case: When you need to sort an array in alphabetical order.
Reverse an Array
Reverse reverses items in the array, then returns the array in its new order. The last item in the array becomes the first, first to last item becomes the second, and so on.
Use case: When you are in a coding challenge interview and they ask you to reverse an array.
Check if Item is in Array Using Includes
Includes array method checks the array for the value in parenthesis and returns
false. True if
includes found a match and false if it did not.
Use case: When you need to check if Oranges are already in your grocery list array.
Bonus: Iterate through an Array Using forEach
ForEach loops through each item in the array and executes the declared function. If there are 4 items in the array,
forEach will run 4 times.
Use case: When you need to check the length of each item in the array.
Those are what I classify as
level 2 array methods.
I hope this article was quick, easy to follow, and helped you learn. Let me know if I need to expand on something or explain it better (in the comments section below).
Next up… Level 3 Array Methods.