C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
JavaScript TypedArray reduce() MethodThe JavaScript reduce() method reduces the elements of an array into a single value and the returned value of the function is stored in an accumulator and each element in the array (from left to right) has to reduce it to a single value. Note: Calling reduce() on an empty array without an initial value is an error.Syntax:array.reduce(function(total, currentValue, index, arr), initialValue) Parameters:Total(required): The previously returned value of the function. CurrentValue(Required): The value of the current element. Index(Optional): The index of the current element being processed in the array. Starts at index 0. Arr(Optional): The array reduce() was called upon. InitialValue(Optional): A value to be passed to the function as the initial value. Return value:Return the reduced single value of the array. Browser Support:
Example 1JavaScript reduce() Method <script type="text/javascript"> // JavaScript to illustrate reduce() method let JavaTpoint =[10,20,30]; // find the sum of all the elements let sum = JavaTpoint.reduce(function(passedIn, item) { return passedIn + item; // 0 is intial value },0); document.write('Array sum is ',sum,'\n'); // expected output: JavaTpoint [Output: 60] Output: 60 Example 2JavaScript reduce(initialValue) Method <script type="text/javascript"> // JavaScript to illustrate reduce() method let JavaTpoint =[10,20,30]; // find the sum of all the elements let sum=JavaTpoint.reduce(function(passedIn, item) { return passedIn + item; // 5 is intial value },5); document.write('Array sum is ',sum,'\n'); // expected output: JavaTpoint [Output: 65] </script> Output: 65 Example 3JavaScript reduce() Method <script> // JavaScript to illustrate reduce() method // Taking some array as the element of an array "A" var A = [ ['Java','MongoDB' ], ['python','C'], [ 'RDBMS', 'C++' ] ]; // Calling array.reduce() function a = A.reduce((previousValue, currentValue) => previousValue.concat(currentValue)); // printing result document.write(a); // expected output: Java,MongoDB,python,C,RDBMS,C++ </script> Output: Java, MongoDB, python, C, RDBMS, C++
Next TopicJavaScript TypedArray Object
|