menu
techminis

A naukri.com initiative

google-web-stories
Home

>

Programming News

>

Understand...
source image

Dev

1M

read

228

img
dot

Image Credit: Dev

Understanding `filter`, `map`, and `reduce` in JavaScript

  • filter(): Selecting Specific Elements - The filter() method creates a new array containing elements from the original array that satisfy a specified condition.
  • map(): Transforming Array Elements - The map() method creates a new array by applying a function to each element of the original array.
  • reduce(): Accumulating Values - The reduce() method applies a function against an accumulator and each element in the array to reduce it to a single value.
  • filter() Example: const numbers = [1, 2, 3, 4, 5]; const evenNumbers = numbers.filter(num => num % 2 === 0); console.log(evenNumbers); // Output: [2, 4]
  • map() Example: const numbers = [1, 2, 3, 4, 5]; const squaredNumbers = numbers.map(num => num * num); console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]
  • reduce() Example: const numbers = [1, 2, 3, 4, 5]; const sum = numbers.reduce((acc, num) => acc + num, 0); console.log(sum); // Output: 15
  • filter() - Use filter when you need to exclude certain items based on a condition.
  • map() - Use map when you want to transform each item into a new value.
  • reduce() - Use reduce when you need to compute a single result from a list of items.
  • Mastering filter, map, and reduce is essential for writing efficient and modern JavaScript.

Read Full Article

like

13 Likes

For uninterrupted reading, download the app