Using underscore js reduces

How does underscorejs reduce ?

Just get _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0); (result 6 ).

But how do other optional parameters work? The docs say:

The memo is the initial state of contraction, and each subsequent step must be returned by the iterator. Four arguments are passed to the iterator: a memo, then the value and index (or key) of the iteration, and finally a link to the entire list.

But I do not understand. I tried using reduce for the following problem, and I could not understand:

 var input = [{"score": 2, "name": "Jon", "venue": "A"}, {"score": 3, "name": "Jeff", "venue":"A"}, {"score": 4, "name": "Jon", "venue":"B"}, {"score": 4, "name": "Jeff", "venue":"B"}]; var output = [{"score": 6, "name":"Jon", "venue": ["A", "B"]}, {"score": 7, "name":"Jeff", "venue": ["A", "B"]}]; 

How can I get output using _reduce for input? And it really will help how it works inside to reduce.

+4
source share
2 answers

Reduction takes a list of values ​​and reduces it to a single value. What you are trying to do is not just diminish. You are trying to create the first group (by name), and then reduce each group. A possible implementation would be something like this when you first group and then map each group to a reduction operation, which accumulates the score and adds the venue.

 var input = [ {"score": 2, "name": "Jon", "venue": "A"}, {"score": 3, "name": "Jeff", "venue":"A"}, {"score": 4, "name": "Jon", "venue":"B"}, {"score": 4, "name": "Jeff", "venue":"B"}]; var output = _.map(_.groupBy(input, "name"), function(group, name) { return _.reduce(group, function(memo, elem) { memo.score += elem.score; memo.venue.push(elem.venue); return memo; }, { name: name, score: 0, venue: [] }); }); 
+9
source

Instead of reduce try using simple and simple each as follows:

_.each allows a third parameter for the context. So for example:

 var input = ["Alice", "Bob", "Charlie"]; var context = {}; _.each(input, function(o,i) { this[i] = o; }, context); console.log(context) //=> {1: "Alice", 2: "Bob", 3: "Charlie"} 

Ruby has a new call to each_with_object , similar to the shortcut for this exact template, where the memo does not necessarily return a value (in fact, my function returns nothing!); but underlining simplifies its API design by simply allowing context for the function as the third parameter.

You can use the abbreviation, but you will need to return the note every time, making it a little less elegant IMHO.

+1
source

Source: https://habr.com/ru/post/1494843/


All Articles