Open In App

Underscore.js _.frequencies() Method

Last Updated : 04 Aug, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
// Array
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




// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
// Array
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




// Defining underscore contrib variable
var _ = require('underscore-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,];
  
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
Previous
Next
Share your thoughts in the comments

Similar Reads