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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);

chevron_right


Output: 

Original Array :  []
Generated Mapping Object:  {}

Example 3: This method works fine with integer array.

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);

chevron_right


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 }

 

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.