Explain the difference between "map", "filter", and "reduce" in JavaScript.
Explain the difference between "map", "filter", and "reduce" in JavaScript.
17315-May-2023
Updated on 15-May-2023
Home / DeveloperSection / Forums / Explain the difference between "map", "filter", and "reduce" in JavaScript.
Explain the difference between "map", "filter", and "reduce" in JavaScript.
Aryan Kumar
15-May-2023Sure.
Map, filter, and reduce are all higher-order functions in JavaScript. They are used to iterate over an array and perform a transformation or computation. Each will return a new array based on the result of the function.
Map
The map() function iterates over an array and applies a function to each element. The function is called with the element as its argument, and the return value of the function is used to create a new element in the resulting array.
For example, the following code uses map() to double the values in an array:
Code snippet
Filter
The filter() function iterates over an array and returns a new array containing only the elements that meet a certain condition. The condition is specified as a function, which is called with each element as its argument. The function returns a Boolean value, and only the elements for which the function returns true are included in the new array.
For example, the following code uses filter() to return an array containing only the even numbers in an array:
Code snippet
Reduce
The reduce() function iterates over an array and applies a function to each element, starting with an initial value. The function is called with the current value of the accumulator and the current element as its arguments. The return value of the function is used to update the accumulator. The process continues until all elements in the array have been processed. The final value of the accumulator is returned.
For example, the following code uses reduce() to calculate the sum of the elements in an array:
Code snippet