JavaScript TypedArray reduce() Method

The reduce method in JavaScript condenses the elements of an array or a TypedArray into a singular value. The outcome produced by this function is held in an accumulator, and every element in the array is processed sequentially (from left to right) until they are combined into one value.

Note: Calling reduce on an empty array without an initial value is an error.

What is reduce on TypedArray?

The reduce function on a TypedArray executes a reducer function on every element within the TypedArray, condensing the elements into a single output value by processing them in a sequential manner.

Syntax:

Example

typedArray.reduce(function(accumulator, currentValue, index, array), initialValue)

Parameters:

accumulator (mandatory): The result that has been accumulated from the prior execution of the callback function, or the initial value if it has been specified.

currentValue (Mandatory): The value associated with the current element that is under processing.

index (Optional): Represents the position of the element currently being handled within the array. It begins at position 0.

array (Optional): The TypedArray instance that the reduce method is executed on.

initialValue (Optional): This is a value intended to be provided to the function as its starting point.

Return value:

Return the reduced single value of the array.

Example 1

Below is an illustration of the reduce method utilized with JavaScript TypedArray.

Example

Example

let pyVisualizer = new Int8Array([10, 20, 30]);  



// Find the sum of all the elements   

let sum = arr.reduce(function(passedIn, item) {  

    return passedIn + item;  

}, 0);   // initial value = 0  



console.log("Sum = " + sum);

Output:

Output

Sum = 60

Explanation:

Here is a JavaScript illustration demonstrating the application of the reduce method to compute the total of all elements within the numbers array, which contains the values 10, 20, and 30. The reduce method requires a callback function and an initial value of 0. The callback function takes two parameters: the current element and the cumulative total. As the function iterates through the array, it aggregates each element, contributing to the cumulative total.

Example 2

We will examine an illustration of the reduce function with an initialValue supplied.

Example

Example

let pyVisualizer = new Int8Array([10, 20, 30]);



// find the sum of all the elements with initial value 5  

let sum = arr.reduce(function(accumulator, item) {  

    return accumulator + item;  

}, 5);   // initial value = 5  



console.log("Sum with initial value = " + sum);

Output:

Output

Sum with initial value = 65

Explanation:

In the following JavaScript snippet, we utilize the reduce method to compute the cumulative total of the elements within our numbers array that contains the values 10, 20, and 30. The reduce function accepts a second parameter, which we will assign the value of 5. This function iterates through each item in the array, progressively summing it with the preceding value. For instance, we initiate the calculation by adding 5 + 10 to obtain 15, followed by 15 + 20, resulting in 35, and finally, 35 + 30 yields a total of 65. The final sum, which represents the total of all three elements in the numbers array added to the initial value of 5, is captured in the variable named sum.

Example 3

In this instance, we will demonstrate how to consolidate an array of TypedArrays into a single TypedArray by utilizing the reduce function.

Example

Example

// Creating an array of TypedArrays

let A = [

  new Int8Array([1, 2]),

  new Int8Array([3, 4]),

  new Int8Array([5, 6])

];



// Using reduce() to merge into one TypedArray

let flatArray = A.reduce((prev, curr) => {

  // Create a new TypedArray with combined length

  let merged = new Int8Array(prev.length + curr.length);



  // Copy previous elements

  merged.set(prev, 0);



  // Copy current elements after prev

  merged.set(curr, prev.length);



  return merged;

});



console.log(flatArray);

Output:

Output

Int8Array [ 1, 2, 3, 4, 5, 6 ]

Explanation:

In the preceding code, A serves as a standard array comprising several Int8Array instances. At each iteration, a new Int8Array is instantiated with a total length that encompasses the lengths of both the previous and current arrays. The method .set is employed to copy the contents of these arrays, resulting in a merged array. The ultimate outcome is a singular, flattened typed array represented as [1, 2, 3, 4, 5, 6].

Uses of TypedArray reduce Method in JavaScript

The TypedArray reduce method in JavaScript has a variety of applications. A few examples include:

1. Calculating a sum or aggregate

This represents a typical scenario in which the reduce function iterates over the array to accumulate a total or compute another aggregated value, such as a product, average, and so forth.

Example

Example

const num = new Int32Array([1, 2, 3, 4, 5]);

const sum = num.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(sum);

Output:

Explanation:

This script creates an Int32Array containing the integers from 1 to 5 and computes the total of these values utilizing the reduce method. The reduce function iterates through each element, adding it to an accumulator. The accumulator represents the value from the previous iteration, and it is initialized to 0, which serves as the first argument in the reduce function. The resulting total is stored in the variable sum and subsequently displayed in the console. The output shown will be 15.

2. Finding Minimum or Maximum Values

In a comparable fashion, the reduce function can likewise be employed to efficiently identify either the maximum or minimum value within the typed array.

Example

Example

const temper = new Float64Array([25.5, 28.1, 22.0, 30.2]);

const maxTemp = temper.reduce((max, current) => Math.max(max, current), -Infinity);

console.log (maxTemp);

Output:

Explanation:

This script generates a Float64Array that holds temperature measurements. It employs the reduce function to determine the highest temperature by examining the array of temperature values, comparing each entry against the current maximum using Math.max, and consolidating its elements into one maximum value. The reduction starts from -Infinity. The resulting maximum temperature is stored in a variable named maxTemp. Subsequently, it outputs the value of maxTemp, which is 30.2, to the console.

3. Transforming an array into an object

The reduce function is capable of generating an object from a typed array by traversing through each element of the typed array and appending properties based on those elements. This functionality is particularly beneficial for tasks such as aggregation or counting.

Example

Example

const colors = new Uint8Array([0, 0, 1, 0, 1, 2]); 

const colorCounts = colors.reduce((counts, color) => {

    counts[color] = (counts[color] || 0) + 1;

    return counts;

}, {});

console.log (colorCounts);

Output:

Output

{ '0': 3, '1': 2, '2': 1 }

Explanation:

In this demonstration, a Uint8Array containing color codes (for instance, 0, 1, 2) is generated. The reduce function is utilized to tally the frequency of each color and records the findings in an object.

Browser Support:

Browser Version
Chrome 45+
Safari 10.1+
Firefox 38+
Opera 32+
Edge 12+

Conclusion

The TypedArray.prototype.reduce method in JavaScript provides a means for developers to proficiently traverse the elements of a TypedArray, condensing it into a singular value via a specified callback function. This method systematically applies a reduction function to each element, enabling a variety of reductions to be performed. These can include simple tasks such as calculating sums and averages, as well as more complex operations like computing dot products.

It enables you to carry out intricate aggregations using concise and adaptable syntax; however, it is essential to be mindful of performance implications, as it can vary significantly based on the dataset's size. Furthermore, it is crucial to provide the correct initial accumulator value because if the TypedArray is devoid of elements, you may encounter unforeseen results depending on how your implementation is structured.

In summary, the reduce method serves as a crucial function when utilizing TypedArrays. When it comes to managing numerical data, it offers significant efficiency and adaptability within the dataset; however, it must be used with careful consideration.

Frequently Asked Questions (FAQs)

  1. What is the function of the reduce method?

It iterates through the elements of a TypedArray, applying a "reducer" callback function to each item sequentially, ultimately consolidating them into a single value. This final output can be a number, an object, another TypedArray, or any other data type.

  1. What parameters does the callback function accept?

The callback function that you provide to the reduce method takes in four parameters:

accumulator: The result obtained from the preceding call to the callback function, or initialValue, if it has been provided.

currentValue: The element currently being processed within the TypedArray.

currentIndex: The position of the currentValue within the TypedArray.

array: The TypedArray that the reduce method has been invoked upon.

  1. What constitutes the Initial Value?

In cases where the initialValue is not specified, the first element of the TypedArray serves as the accumulator, and the iteration over each element begins with the second element of the TypedArray. Conversely, if the TypedArray is devoid of elements and no initialValue is given, invoking the reduce method will result in a TypeError being thrown.

  1. Does reduce alter the original TypedArray?

No, the reduce method does not alter the TypedArray on which it is invoked. Instead, it generates and returns a new single value that represents the cumulative outcome.

  1. What are some frequent applications of reduce?

Some typical use cases of reduce are:

  • To get the sum or product of all values.
  • To flatten a nested array of TypedArrays.
  • To count how many times certain values occur.
  • To group elements into groups according to some rule.
  • To convert a TypedArray into a new data structure (e.g., an object).
  1. How does reduce differ from forEach, map, or filter?
  • The forEach function loops through elements but does not return a value.
  • The map function returns a new TypedArray of the same length with each element being the result of the callback function.
  • The filter function returns a new TypedArray with elements that pass certain criteria.
  • The reduce function takes elements and reduces them to a single value.

Input Required

This code uses input(). Please provide values below: