JavaScript | typedArray.reduce() with Examples

The typedArray.reduce() is an inbuilt function in JavaScript which is used to reduce each element of the typedArray from left to right into a single value.
Syntax:

typedArray.reduce(callback)

Parameters: It accept a parameter callback function which accept some parameters specified below-

  • previousValue: It is the previously returned value.
  • currentValue: It is the current element being processed in the typedArray.

Return value: It returns the result of the reduce() function.



JavaScript code to show the working of this function:

Code #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    
  // Creating some typedArray
  const A = new Uint8Array([ 1, 2, 3, 4]);
  const B = new Uint8Array([5, 6, 7]);
  const C = new Uint8Array([1, 3, 5]);
  const D = new Uint8Array([2, 4, 6, 8]);
  
  // Calling sum() function 
  function sum(previousValue, currentValue) {
  return previousValue + currentValue;
  }
  
  // Printing reduced value of the given typedArray
  document.write(A.reduce(sum) +"<br>");
  document.write(B.reduce(sum) +"<br>");
  document.write(C.reduce(sum) +"<br>");
  document.write(D.reduce(sum));
     
     
</script>

chevron_right


Output:

10
18
9
20


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.