Lodash _.frequencies() 方法
Lodash _.frequencies() 方法接受一个数组并返回一个映射对象,其键是数组元素的值,值是出现在该数组中的该键的计数。
句法:
_.frequencies( array );
参数:此方法接受如上所述和如下所述的单个参数:
- 数组:要从中创建映射的给定数组。
返回值:该方法返回一个创建的映射对象。
注意:这在普通 JavaScript 中不起作用,因为它需要安装 lodash.js contrib 库。 Lodash.js contrib 库可以使用以下命令安装:
npm install lodash-contrib
示例 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);
输出:
Original Array : [“Geeks”, “Geeks”, “GFG”, “Computer_Science_Portal”, “Geeks”, “GFG”]
Frequency of elements : Object {Computer_Science_Portal: 1, GFG: 2, Geeks: 3}
示例 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);
输出:
Original Array : []
Frequency of elements : Object {}
示例 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);
输出:
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}