Underscore.js _.frequencies() Method
Last Updated :
04 Aug, 2020
The _.frequencies() method takes an array and returns a mapping object whose keys are the values of the array’s elements and values are counts of that key appeared in that array.
Syntax:
_.frequencies( array );
Parameters: This method accepts a single parameter as mentioned above and described below:
- array: The given array from which mapping is to be created.
Return Value: This method returns a created mapping object.
Note: This will not work in normal JavaScript because it requires the underscore.js contrib library to be installed.
underscore.js contrib library can be installed using npm install underscore-contrib –save.
Example 1:
Javascript
var _ = require( 'underscore-contrib' );
var array = [ "Geeks" , "Geeks" , "GFG" ,
"Computer_Science_Portal" ,
"Geeks" , "GFG" ];
var obj = _.frequencies(array);
console.log( "Original Array : " , array);
console.log( "Generated Mapping Object: " , obj);
|
Output:
Original Array : [ 'Geeks', 'Geeks', 'GFG',
'Computer_Science_Portal', 'Geeks', 'GFG' ]
Generated Mapping Object: { Geeks: 3, GFG: 2,
Computer_Science_Portal: 1 }
Example 2: For an empty array, an empty object is created.
Javascript
var _ = require( 'underscore-contrib' );
var array = [];
var obj = _.frequencies(array);
console.log( "Original Array : " , array);
console.log( "Generated Mapping Object: " , obj);
|
Output:
Original Array : []
Generated Mapping Object: {}
Example 3: This method works fine with integer array.
Javascript
var _ = require( 'underscore-contrib' );
var array = [1,1,1,1,1,1,3,3,3,4,4,
4,5,5,5,6,6,6,6,7,7,];
var obj = _.frequencies(array);
console.log( "Original Array : " , array);
console.log( "Generated Mapping Object: " , obj);
|
Output:
Original Array : [
1, 1, 1, 1, 1, 1, 3,
3, 3, 4, 4, 4, 5, 5,
5, 6, 6, 6, 6, 7, 7
]
Generated Mapping Object: { '1': 6, '3': 3, '4':
3, '5': 3, '6': 4, '7': 2 }
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...