📜  Underscore.js _.frequencies() 方法

📅  最后修改于: 2022-05-13 01:56:53.063000             🧑  作者: Mango

Underscore.js _.frequencies() 方法

_.frequencies() 方法接受一个数组并返回一个映射对象,其键是数组元素的值,值是出现在该数组中的该键的计数。

句法:

_.frequencies( array );

参数:此方法接受如上所述和如下所述的单个参数:

  • 数组:要从中创建映射的给定数组。

返回值:该方法返回一个创建的映射对象。

注意:这在普通 JavaScript 中不起作用,因为它需要安装 underscore.js contrib 库。

underscore.js contrib 库可以使用npm install underscore-contrib –save 安装。

示例 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);


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


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


输出:

Original Array :  [ 'Geeks', 'Geeks', 'GFG', 
'Computer_Science_Portal', 'Geeks', 'GFG' ]
Generated Mapping Object:  { Geeks: 3, GFG: 2, 
Computer_Science_Portal: 1 }

示例 2:对于一个空数组,创建一个空对象。

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

输出:

Original Array :  []
Generated Mapping Object:  {}

示例 3:此方法适用于整数数组。

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

输出:

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 }