How to use array reduce in JavaScript
In this article, I am going to explain about reduce method in JavaScript.
Array reduce method in JavaScript
Reduce method in JavaScript applies one-element arrays are turned into their unique element, while multiple-element array are return untouched.
Syntax of reduce method
array.reduce(callback[, initalvalue]);
|
Parameters in reduce method:
Return value in reduce method
It returns an object that contains the accumulated result from the last call to the callback function.
Exception in reduce method
If callback argument is not a function object and array contain no element and initial value is not provide, A TypeError exception is fire.
There are the following callback parameter:
Parameter |
Value |
Previous value |
The value from previous call to the callback function. |
Current value |
The value of the current array element. |
Current index |
The numeric index of the current array element. |
Example of reduce method
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Array Reduce Method</title>
</head>
<body>
<script type="text/javascript">
function ReduceMeth(previousValue, currentValue) {
return previousValue + ":" + currentValue;
}
var elements = ["Java", "Script", 111, 222];
var result = elements.reduce(ReduceMeth);
document.write(result);
</script>
</body>
</html>
|
Output:
Ask Your Question
Got a programming related question? You may want to post your question here