Skip to content

Instantly share code, notes, and snippets.

@lucas-barake
Last active August 26, 2023 13:13
Show Gist options
  • Select an option

  • Save lucas-barake/0dc600b9c1a04587f39ef777f53a40a3 to your computer and use it in GitHub Desktop.

Select an option

Save lucas-barake/0dc600b9c1a04587f39ef777f53a40a3 to your computer and use it in GitHub Desktop.
JavaScript: When to use array methods

.forEach()

The .forEach() method is used to execute a function for each element in the array.

["🍐", "🍎", "🍐", "🍎", "🍎"].forEach((fruit) => console.log(fruit)) -> 🍐, 🍎, 🍐, 🍎, 🍎

.filter()

The .filter() method is used to create a new array with only the elements that pass a test function. If the function returns true, the element is kept in the new array. If the function returns false, the element is removed from the new array. You can think of the .filter as a .where instead.

["🍐", "🍎", "🍐", "🍎", "🍎"].filter((fruit) => fruit === "🍎") -> ["🍎", "🍎", "🍎"]

.map()

The .map() method is used to create a new array with the results of applying a function to every element in the array.

["🍐", "🍎", "🍐", "🍎", "🍎"].map((fruit) => fruit + "πŸ₯§") -> ["🍐πŸ₯§", "🍎πŸ₯§", "🍐πŸ₯§", "🍎πŸ₯§", "🍎πŸ₯§"]

.every()

The .every() method is used to check if every element in the array satisfies a condition.

["🍐", "🍎", "🍐", "🍎", "🍎"].every((fruit) => fruit === "🍎") -> false

.some()

The .some() method is used to check if at least one element in the array satisfies a condition. The method returns true if any element passes the test, and false otherwise.

["🍐", "🍎", "🍐", "🍎", "🍎"].some((fruit) => fruit === "🍐") -> true

.find()

The .find() method is used to find the first element in the array that satisfies a condition. The method returns the element if found, and undefined otherwise.

["🍐", "🍎", "🍐", "🍎", "🍎"].find((fruit) => fruit === "πŸ₯") -> undefined

.findIndex()

The .findIndex() method is used to find the index of the first element in the array that satisfies a condition. The method returns the index if found, and -1 otherwise.

["🍐", "🍎", "🍐", "🍎", "🍎"].findIndex((fruit) => fruit === "🍐") -> 0

.reduce()

The .reduce() method is used to apply a function to each element in the array and accumulate a single value. The function takes two arguments: an accumulator and a current element. The accumulator stores the result of previous iterations, and the current element is the one being processed.

const words = ["spray", "limit", "elite", "exuberant", "destruction", "present"];
const longestWord = words.reduce((prevLongestWord, currentWord) =>
  currentWord.length > prevLongestWord.length ? currentWord : prevLongestWord
);
console.log(longestWord); // destruction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment