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:
// Defining underscore lodash variable var _ = require('lodash-contrib'); // Array var array = ["Geeks", "Geeks", "GFG", "Computer_Science_Portal", "Geeks", "GFG"]; var obj = _.frequencies(array); // Printing object 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:
// Defining underscore lodash variable var _ = require('lodash-contrib'); // Array var array = []; var obj = _.frequencies(array); // Printing object console.log("Original Array : ", array); console.log("Frequency of elements : ", obj); |
Output:
Original Array : []
Frequency of elements : Object {}
Example 3:
// Defining underscore lodash variable var _ = require('lodash-contrib'); // Array 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); // Printing 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}
