JavaScript ๐ก
14 Array Methods that will make your life easier. Explanation and examples below.
๐งต๐
๐ธ map
The map() method creates a new array populated with the return value of the callback function for each element in the array.
๐ธ forEach
The forEach() method executes a provided function once for each array element. The callback function does not expect a return value, and the forEach() method itself also returns undefined.
๐ธ filter
The filter() method creates a new array containing only the elements that "pass the test" implemented by the callback function. We call this type of callback a predicate function.
๐ธ find
The find() method behaves similarly to the filter() method, but it only returns a single element. This method will stop at the first element that "pass the test", and return that. If none exists, it will return undefined.
๐ธ findIndex
The findIndex() method behaves similarly to the find() method, but it returns an index instead of the element, This method will stop at the first element that "pass the test", and return its index. If none exists, it will return -1.
๐ธ reduce
The reduce() method takes a callback with (at least) two arguments: An accumulator and the current element.
For each iteration, the return value of the callback function is passed on as the accumulator argument of the next iteration.
๐ธ some
The some() method takes a predicate function and return true if any of the elements in the array "passes the test".
๐ธ every
The every() method takes a predicate function and returns true if all of the elements in the array "pass the test".
๐ธ includes
The includes() method checks if an array includes a certain value among its elements, returning true or false.
๐ธ fill
The fill() method replaces all the elements in an array to a given value.
๐ธ reverse
The reverse() method reverses the order of the elements in the array.
๐ธ flat
The flat() method creates a new array with all sub-array elements flattened into it. You can specify a depth. The default is 1.
๐ธ flatMap
The flatMap() method applies a callback to each element of the array and then flatten the result into an array. It combines flat() and map() in one function.
๐ธ sort
The sort() method is used to sort the elements of an array and returning the sorting array. Be aware that this method is mutating the original array.
If you want to learn more about JavaScript Array Methods, be sure to watch this YouTube video.
I reimplement forEach, map, filter, and reduce.
This often comes up in job interviews - acing this challenge will give you some serious points ๐ฅ