Welcome to this comprehensive guide on Functional Programming (FP) Map, Filter, and Reduce! These are powerful tools that can help you manipulate data in your JavaScript projects efficiently. Let's dive in! 🎯
Functional Programming (FP) is a programming paradigm that emphasizes the use of functions as the primary building blocks. Unlike traditional imperative programming, FP is declarative, meaning you describe what you want to achieve rather than how to achieve it.
Array.prototype.map() is a built-in JavaScript function that creates a new array with the results of calling a provided function on each element in the original array.
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(num => num * num);
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]Array.prototype.filter() is a built-in JavaScript function that creates a new array with all elements that pass the test provided by the callback function.
const numbers = [1, 2, 3, 4, 5];
const oddNumbers = numbers.filter(num => num % 2 !== 0);
console.log(oddNumbers); // Output: [1, 3]Array.prototype.reduce() is a built-in JavaScript function that applies a function against an accumulator and each element in the array to reduce it to a single output value.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // Output: 15We'll dive into practical examples for each function to help you understand their usage better.
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(num => num * num);
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]const numbers = [1, 2, 3, 4, 5];
const oddNumbers = numbers.filter(num => num % 2 !== 0);
console.log(oddNumbers); // Output: [1, 3]const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // Output: 15In this section, we'll explore more complex examples for each function.
const users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Doe' }
];
const names = users.map(user => user.name);
console.log(names); // Output: ['John', 'Jane', 'Doe']const users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Doe' }
];
const jane = users.filter(user => user.name === 'Jane');
console.log(jane); // Output: [{ id: 2, name: 'Jane' }]const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((total, num) => total + num, 0);
const average = sum / numbers.length;
console.log(average); // Output: 3