Sunday, December 14, 2025
HomeLanguagesJavascriptUnderscore.js _.frequencies() Method

Underscore.js _.frequencies() Method

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 }

 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32448 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6817 POSTS0 COMMENTS
Nicole Veronica
11954 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12031 POSTS0 COMMENTS
Shaida Kate Naidoo
6955 POSTS0 COMMENTS
Ted Musemwa
7202 POSTS0 COMMENTS
Thapelo Manthata
6899 POSTS0 COMMENTS
Umr Jansen
6883 POSTS0 COMMENTS