Lodash _.frequencies() Method
The Lodash _.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 lodash.js contrib library to be installed. Lodash.js contrib library can be installed using the following command:
npm install lodash-contrib
Example 1:
var _ = require( 'lodash-contrib' );
var array = [ "Geeks" , "Geeks" , "GFG" ,
"Computer_Science_Portal" ,
"Geeks" , "GFG" ];
var obj = _.frequencies(array);
console.log( "Original Array : " , array);
console.log( "Frequency of elements : " , obj);
|
Output:
Original Array : [“Geeks”, “Geeks”, “GFG”, “Computer_Science_Portal”, “Geeks”, “GFG”]
Frequency of elements : Object {Computer_Science_Portal: 1, GFG: 2, Geeks: 3}
Example 2:
var _ = require( 'lodash-contrib' );
var array = [];
var obj = _.frequencies(array);
console.log( "Original Array : " , array);
console.log( "Frequency of elements : " , obj);
|
Output:
Original Array : []
Frequency of elements : Object {}
Example 3:
var _ = require( 'lodash-contrib' );
var array = [1, 1, 1, 1, 1, 1, 3,
3, 3, 4, 4, 4, 5, 5, 5,
6, 6, 6, 6, 7, 7, 8, 10];
var obj = _.frequencies(array);
console.log( "Original Array : " , array);
console.log( "Frequency of elements : " , 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, 8, 10]
Frequency of elements : Object {1: 6, 3: 3, 4: 3, 5: 3, 6: 4, 7: 2, 8: 1, 10: 1}
Last Updated :
30 Sep, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...