In the world of JavaScript programming, the ability to manipulate arrays efficiently and elegantly is a skill that separates novice developers from seasoned experts.
map
, filter
, and reduce
These three versatile functions are not only essential tools in a JavaScript developer's arsenal but also shining examples of the functional programming paradigm.
let's learn these three very important functions in a step-by-step manner
Map
The
map
function creates a new array by applying a given function to each element of an existing array.It does not modify the original array; instead, it returns a new array with the results.
const numbers = [1,2,3,4]; const doubledNumbers = numbers.map((num) => num * 2); console.log(doubledNumbers); //output - [1,4,6,8]
Filter
The
filter
function creates a new array containing all the elements that pass a test implemented by the provided function.It does not modify the original array; instead, it returns a new array with the results.
const numbers = [1, 2, 3, 4, 5]; const evenNumbers = numbers.filter((num) => num % 2 === 0); console.log(evenNumbers); //output [2,4]
Reduce
The
reduce
function reduces an array to a single value by applying a function to each element and accumulating the result.It takes a callback function that has an accumulator (the accumulated result) and the current element as arguments.
You can also provide an initial value for the accumulator.
const numbers = [1, 2, 3, 4, 5]; const sum = numbers.reduce((accumulator, current) { return accumulator + current }, 0); console.log(sum); //output - 15
The second parameter 0 is the initial value given to the accumulator.
Conclusion
In summary, map
transforms each element of an array and returns a new array, filter
selects elements that meet a specific condition, and reduce
accumulates the elements into a single value. These functions are powerful tools for working with arrays functionally and concisely, improving code readability and maintainability.