JavaScript Array Methods
JavaScript Array Methods
JavaScript has so many array methods, yet I repeatedly come back to using just map or filter. I'm going to list them here so I don't forget.
- map():
- What it does? Transforms each item in an array and returns a new array with the transformed values.
- Example: It's like giving each item in a list a makeover resulting in a new list.
- forEach():
- What it does? Executes a provided function once for each array element.
- Example: Consider you have an array of names, and you want to print each name to the console. You can use forEach() to loop through the array and print each name individually.
- filter():
- What it does? Selects specific items from an array based on a condition and returns a new array with only those items.
- Example: Choosing only takis from a mix of chips, leaving out the rest.
- reduce():
- What it does? Combines all items into a single value.
- Example: It's like a bank adding up coins to show total amount.
- find():
- What it does? Locates and retrieves the first matching item.
- Example: It's like a search function, but it only returns the first match.
- findIndex():
- What it does? Returns the index of the first element in an array that satisfies a condition.
- Example: Imagine you have an array of ages, and you want to find the index of the first person who is older than 65. You can use findIndex() to locate and get the index of that person in the array.
- includes():
- What it does? Checks if an array includes a certain value among its entries.
- Example: Seeing if a shopping list includes chocolates before going to the store.
- some():
- What it does? Checks if at least one item meets a condition.
- Example: Quickly peeking to see if there's a chocolate left in a box before sharing.
- every():
- What it does? Checks if all items meet a condition.
- Example: Asking everyone present whether they're all ready to go.
- concat():
- What it does? Combines two or more arrays.
- Example: Combine two momos to make one big momo.
- sort():
- What it does? Sorts the elements of an array in place and returns the sorted array.
- Example: Sorting a list of names alphabetically.
- flatMap():
- What it does? Maps each element to a new array and flattens it into a new array with the same elements.
- Example: You have an array of arrays, and you want to flatten it into a single array.
- slice():
- What it does? Extracts a section of an array and returns a new array.
- Example: Getting a portion of chocolate from a Dairy Milk.
- splice():
- What it does? Changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
- Example: Rearranging a deck of cards by removing some and inserting others at specific positions.