Grammar
_.countby (list, iteratee, [context])
Description
Sorts a list of groups, and returns a count of the number of objects in each group. Similar to GroupBy, but does not return the value of the list, but returns the number of values in that group. Just like the classified statistics in Excel
- The list is a collection of loops, such as arrays, objects, strings, arguments, and so on.
- Iteratee iterators can be either a function or a string, etc.
- Iteratee has three parameters (element, index, list)
- Iteratee need to have a return
- Context execution contexts, changed to this within iteratee
Sample code example one: according to iteratee classification statistics
var function (num) { return num% 2 = = = 0;}); // The qualifying key is true and the non-conforming key is false. //= Object {false:3, true:2}
Example two: The object that returns the result specifies key
var function (num) { return num% 2 = = 0? ' Even ': ' Odd '//= = Object {odd:3, even:2}
Example three: Changing the This in the Iteratee
var function (num) { console.log (this//5 times = = Object {no:3} return This 3//= Object {false:3, true:2}
Example four: iteratee three parameters & Don't forget to return
var function (element, index, list) { Console.log (element, index, list); // = a 0 ABC // = b 1 ABC // = C 2 ABC //= Object {Undefined:3}
Iteratee can be a property of an object
var list = [' One ', ' one ', ' one ', ' three ', ' four ', ' five ', ' six ', ' seven ', ' eight ', ' nine ', ' ten ']; var grouped = _.countby (list, ' length '//= = = Object {3:4, 4:3, 5:3}
Iteratee can be the object's key
var list = [{x: ' a '}, {x: ' B '}, {x: ' A '}]; var grouped = _.countby (list, ' x '//= = = Object {a:2, b:1}
Iteratee can be an object
var list = [{x:0, y:0}, {x:0, y:1}, {x:1, y:1}]; var grouped = _.countby (list, {x:0//= = = Object {true:2, false:1}
Do not pass the iteratee to the value to classify the statistic
var parity = _.countby (' abcab '//= = Object {a:2, b:2, c:1}
Non-collection Return {}
// = = Object {} // = = Object {}Console.log (_.countby (null//= = Object {}//= =) Object {}Console.log (_.countby (true//= = Object {}Console.log (_.countby ( false // = = Object {}
Underscorejs _.countby (list, iteratee, [context])