JavaScript Array method: reduceRight()
[this page | pdf | back links]
The reduceRight() method (when applied to a
JavaScript
array) reduces
the values of an array to a single value (evaluating from right to left, i.e.
from highest to lowest index).
It
has the following syntax with the following parameters. It returns the
accumulated result from the last call of the function. It does not execute the
function if the array element does not have a value.
array.reduceRight(function(total, currentValue,
index, arr), initialValue)
Parameter
|
Required / Optional
|
Description
|
function(total,
currentValue, index, arr)
|
Required
|
A function to be run
for each element
|
initialValue
|
Optional
|
A value to be passed to
the function to be used as the initial value
|
The function
arguments are:
Parameter
|
Required / Optional
|
Description
|
total
|
Required
|
The initalValue
or the previously returned value of the function
|
currentValue
|
Required
|
The value of the
current element
|
Index
|
Optional
|
The array index of the
current element
|
arr
|
Optional
|
The array object which
the current element belongs to
|
EXAMPLE:
HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse: collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
</tr>
<tr>
<td><code id="Example"></code></td>
<td><code id="Result"></code></td>
</tr>
</table>
<script>
var h = [1, 2, 3];
document.getElementById("Example").innerHTML =
'var h = [1, 2, 3];<br>' +
'function square(tot, x) {<br>' +
' return tot + x * x;<br>' +
'}<br>' +
'var x = h.reduceRight(sumsquare, 5);';
document.getElementById("Result").innerHTML
= h.reduceRight(sumsquare, 5);
function sumsquare(tot,x) {
return tot + x * x;
}
</script>
</body>
</html>
|
FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodArrayReduceRight() {
var h = [1, 2, 3]; return !!h.reduceRight;
} |
NAVIGATION LINKS
Contents | Prev | Next | JavaScript Arrays