Waiting Answer May 18, 2024

What Is the Difference Between Map,Filter,Reduce

What does map() filter() reduce() function do in js.

Answers
2024-06-09 18:08:20

Map:-Transforms each element in an array and returns a new array with the transformed elements.

Ex:- const numbers = [1, 2, 3, 4];

const doubled = numbers.map(num => num * 2);

console.log(doubled); // Outputs: [2, 4, 6,

8]

 

Filter:-Filters elements in an array based on a test (provided as a function) and returns a new array with elements that pass the test.

Ex:- const numbers = [1, 2, 3, 4];

const evens = numbers.filter(num => num % 2 === 0);

console.log(evens); // Outputs: [2,

4]

Reduce:- Reduces an array to a single value by applying a function that accumulates a result over all elements of the array.

Ex:- const numbers = [1, 2, 3, 4];

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

console.log(sum); // Outputs:

10