Lodash _.reductions() Method
Last Updated :
18 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.reductions() method is used to transform an array of elements to an array in which every intermediate value in the folding operation is stored. This method is the same as the _.reduce() method except it returns an array. An array, a function, and a starting value are passed in this method to generate a new array to perform operations on the array.
Syntax:
_.reductions( array, function, start_val )
Parameters: This method accepts three parameters as mentioned above and described below:
- array: It is the array to be worked upon.
- function: It is the function containing the iteration conditions.
- start_val: It is the value passed at starting which further updates on further operations.
Return Value: This method returns a new array.
Note: This will not work in normal JavaScript because it requires the Lodash contrib library to be installed. Lodash contrib library can be installed using npm install lodash-contrib –save
Example 1: In this example, the sum array is generated with the starting value given as 0 which updates on addition operations.
Javascript
var _ = require( 'lodash-contrib' );
var array = [10, 12, 23, 34, 45];
var arr = _.reductions(array, function (st, n) {
return st - n;
}, 0);
console.log( "Generated Array : " );
console.log(arr);
|
Output:
[ -10, -22, -45, -79, -124 ]
Example 2: In this example, a multiplication array will be generated by giving the starting value as 1 which updates on further multiplication.
Javascript
var _ = require( 'lodash-contrib' );
var array = [10, 12, 23, 34, 45];
var arr =_.reductions(array, function (st, n) {
return st * n;
}, 1);
console.log( "Generated Array : " );
console.log(arr);
|
Output:
Generated Array :
[ 10, 120, 2760, 93840, 4222800 ]
Share your thoughts in the comments
Please Login to comment...