The map() method creates a new array by applying a function to each element of the original array. The function can perform any operation on the element, and the new array will contain the result of that operation.
const numbers = [1, 2, 3, 4, 5]; const doubledNumbers = numbers.map(num => num * 2); console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
The filter() method creates a new array by removing elements from the original array that do not pass a certain condition. The condition is determined by a function that is passed as an argument.
const numbers = [1, 2, 3, 4, 5]; const evenNumbers = numbers.filter(num => num % 2 === 0); console.log(evenNumbers); // Output: [2, 4]
The reduce() method takes an array and reduces it to a single value. The value is determined by a function that is passed as an argument. The function takes two arguments, an accumulator and the current element of the array. The accumulator is the accumulated value from previous iterations, and the current element is the current value being processed.
const numbers = [1, 2, 3, 4, 5]; const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue); console.log(sum); // Output: 15
The forEach() method loops through each element of an array and performs a specified action on each element. The action is determined by a function that is passed as an argument.
const numbers = [1, 2, 3, 4, 5]; numbers.forEach(num => console.log(num)); // Output: 1 2 3 4 5
The find() method returns the first element in an array that passes a certain condition. The condition is determined by a function that is passed as an argument.
const numbers = [1, 2, 3, 4, 5]; const evenNumber = numbers.find(num => num % 2 === 0); console.log(evenNumber); // Output: 2
About the author
Joff Tiquez, hailing from Manila, Philippines, is the individual behind the establishment of OSSPH. He is a web developer who strongly supports open source and has been overseeing projects like Vue Stripe for an extended period. To get in touch with Joff, you can visit https://bento.me/jofftiquez.