js reduce
- User
User: js reduce Assistant: The
reducemethod in JavaScript is an array method that executes a reducer function on each element of the array, resulting in a single output value. It is a powerful method for performing calculations, transformations, or aggregations on arrays.Syntax
javascriptarray.reduce((accumulator, currentValue, currentIndex, array) => { // return updated accumulator }, initialValue);Parameters
-
callback: A function that is called for each element in the array. It receives the following arguments:
- accumulator: Accumulates the callback's return values.
- currentValue: The current element being processed in the array.
- currentIndex (optional): The index of the current element being processed (starts from 0).
- array (optional): The original array that
reducewas called upon.
-
initialValue (optional): A value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used, and the callback will start with the second element.
Example Usage
-
Sum of an Array:
javascriptconst numbers = [1, 2, 3, 4]; const sum = numbers.reduce((accumulator, currentValue) => { return accumulator + currentValue; }, 0); console.log(sum); // Output: 10 -
Flattening an Array:
javascriptconst nestedArray = [[1, 2], [3, 4], [5]]; const flattened = nestedArray.reduce((accumulator, currentValue) => { return accumulator.concat(currentValue); }, []); console.log(flattened); // Output: [1, 2, 3, 4, 5] -
Counting Instances of Values in an Object:
javascript
-
- Assistant