Arrays are list-like objects whose prototype provides various methods to perform many operations. Did you ever thought what are the different use-cases where these methods can be used?
The answer to this question can be found using: I WANT TO...
1. Mutate the original array
Add an element
- push(): Adds one or more elements to the end of an array and returns the new length of the array.
- unshift(): Adds one or more elements to the beginning of an array and returns the new length of the array.
Remove an element
- pop(): Removes the last element from an array and returns that element.
- shift(): Removes the first element from an array and returns that element.
- splice(): Changes the contents of an array by removing or replacing existing elements and/or adding new elements.
Others:
- fill(): Changes all elements in an array to a static value.
- sort(): Sorts an array.
- reverse(): Reverses an array.
2. Create a new array from original array
Portion of array
- slice(): Returns a shallow copy of a portion of an array into a new array.
Computed from array.
- map(): Creates a new array from an existing one by applying a function to each one of the elements of the existing array.
- reduce(): Reduces an array of values down to just one value.
- filter(): Takes each element in an array and applies a conditional statement against it. If this conditional returns true, the element gets pushed to the new array.
Merge into array
- concat(): Merges two or more arrays.
Flatten the array:
- flat(): Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
- flatMap(): Returns a new array formed by applying a given callback function to each element of the existing array, and then flattening the result by one level.
3. Find the
Index of element
- findIndex(): Returns the index of the first element in the array that satisfies the given condition. Otherwise, it returns -1.
Array element
- find(): Returns the first element in the array that satisfies the given condition. Otherwise, it returns undefined.
4. Check if array contains an element
Using a condition
- some(): Returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false.
- every(): Returns true if, in the array, it finds all the element returns true for the provided function; otherwise it returns false.
Using a value
- includes(): Checks whether an array includes a certain value, returning true or false as appropriate.
5. Loop the array
- forEach(): Executes a provided function once for each array element.
6. Join the array elements
- join(): Creates and returns a new string by concatenating all of the elements in an array
Top comments (0)