Science Knowings: JavaScript Course For Social Media

Map, Filter, and Reduce in Functional Programming

Lazy Evaluation and Functional Programming

Today, we're diving into functional programming, a paradigm where code is evaluated lazily, meaning it's only executed when needed, leading us to three powerful techniques: Map, Filter, and Reduce.

Map

Map transforms each element in an array by applying a function and returns a new array with the transformed values while preserving the original array's length.

Example: Fahrenheit to Celsius

const celsius = fahrenheit.map(temp => (temp - 32) * 5 / 9)

This will convert an array of Fahrenheit temperatures to Celsius.

Example: Capitalize Strings

const capitalized = strings.map(str => str.charAt(0).toUpperCase() + str.slice(1))

This will capitalize the first letter of each string in an array.

Filter

Filter creates a new array containing elements that pass a given condition, effectively removing falsy values.

Example: Remove Blank Strings

const nonEmptyStrings = strings.filter(str => str)

This will remove all empty strings from an array.

Example: Prime Numbers

const primeNumbers = numbers.filter(num => isPrime(num))

This will filter an array of numbers, returning only prime numbers using a helper function.

Reduce

Reduce collapses an array into a single value by applying a function to each element and the previous accumulated value.

Example: Sum of Numbers

const total = numbers.reduce((acc, num) => acc + num, 0)

This will calculate the sum of all numbers in an array.

Example: Product of Numbers

const product = numbers.reduce((acc, num) => acc * num, 1)

This will calculate the product of all numbers in an array.

Example: Flatten Array

const flatArray = nestedArray.reduce((acc, val) => acc.concat(val), [])

This will flatten a nested array into a single-level array.

Next Topic: Point-free Style

Next, we'll explore Point-free Style, a technique for writing elegant and concise code. It eliminates the need for intermediate variables and function calls, making code easier to read and understand. Follow us for the next session!