As a software engineering student I have learned that a strong foundation is very important in the process of becoming a good developer. The basic concepts you learn at the very beginning will follow you all the way through your career. One of these very important concepts is Array Methods. I have created a small cheatsheet with examples and a brief explanation of some of the methods and what each one of them does.
.push() and .unshift()
Both methods will add an element to an array. The .push() method will ad an element to the end of the array and .unshift() will add an element to the beginning of an array. Example:
.pop() and .shift()
Both methods will remove an element from the array. The .pop() method will remove the last element of an array and .shift() will remove the first element of an array. Example:
The .slice() method will return desired elements in a new array without altering the original array. Let’s suppose we want to specify the start index (2) and the end index (5). Keep in mind (5) is the index before which the slice should end. Example:
The .splice() method allows us to remove elements, add elements, or replace elements (or any combination of the three). Keep in mind that unlike .slice(), .splice() is a destructive method, which means it will alter the original array.
The first parameter (2) defines the position where new elements should be added (spliced in). The second parameter (0) defines how many elements should be removed.
After the first two, every additional argument passed to .splice() will be inserted into the array at the position indicated by the first argument.
Spread operator …
The spread operator, represented by (…) allows us to copy elements of an existing array into a new array. Example:
These built-in methods help us iterate through arrays and are called “iteration methods” or “iterators”. Iterators are methods that are called on arrays to manipulate elements and return some values. Array iteration methods operate on every array item. Example:
This method takes a callback function and will iterate through the array, call the callback on each value, and return the first element in the array that satisfies the condition defined by the function. If no values satisfy the testing function, undefined is returned.
This method returns a new array with all elements that match a certain condition implemented by the callback function.
This method executes a snippet of code (or a function) once for every element of an array. Unlike the other methods we’ve looked at in this section, forEach() doesn't have a built-in return value. As a result, the callback we pass to it can contain whatever functionality we like.
This method will create a new array with elements that have been transformed by the function provided. Example: