Day 6 ✌️| Easy | Commented with Examples ✅
The reduce function is a higher-order function in JavaScript that allows you to reduce an array of values to a single value using a provided function.\nIt takes
The **reduce** function is a higher-order function in JavaScript that allows you to reduce an array of values to a single value using a provided function.\nIt takes three arguments:\nnums: An array of values to be reduced.\nfn: A function that is used to perform the reduction. \nThis function takes two **arguments**, an accumulator and the current value from the array, and returns a new accumulator.\n***init: An optional initial value for the accumulator.***\nThe reduce function works by iterating over each value in the array and applying the provided function to the current accumulator and the current value. \nThe result of this function call becomes the new accumulator, which is then used in the next iteration.\n\nHere\'s an example of using the reduce function to sum the values in an array:\n\n```\nconst nums = [1, 2, 3, 4, 5];\nconst sum = reduce(nums, (acc, val) => acc + val, 0);\nconsole.log(sum); // Output: 15\n\n```\nIn this example, the ***reduce function*** is used to sum the values in the nums array. The fn argument is a function that takes the current accumulator acc and adds the current value val to it.\nThe initial value for the accumulator init is set to 0.\n\nAnother example is to use the ***reduce function*** to find the maximum value in an array:\n\n```\nconst nums = [1, 2, 3, 4, 5];\nconst max = reduce(nums, (acc, val) => Math.max(acc, val), -Infinity);\nconsole.log(max); // Output: 5\n\n```\n\nIn this example, the ***reduce function*** is used to find the maximum value in the nums array. The fn argument is a function that takes the current accumulator acc and the current value val and returns the maximum of the two using the ***Math.max functio***n. The initial value for the accumulator init is set to -Infinity to ensure that any value in the array is greater than the ***initial accumulator valu***e.\n\n***Here is the solution to the given problem :-***\n\n\n```\n\nvar reduce = function(nums, fn, init) {\n    let ans = init;\n  for (let i = 0; i < nums.length; i++) {\n    ans = fn(ans, nums[i]);\n  }\n  return ans;\n};\n```
['Array', 'JavaScript']