Nav*_*ppa 2 javascript arrays frequency object find-occurrences
想象我有一个对象
teaherList = [
{teacherID:1,teacherName:"john"},
{teacherID:2,teacherName:"joe"},
{teacherID:3,teacherName:"jill"},
{teacherID:1,teacherName:"john"},
{teacherID:2,teacherName:"joe"},
{teacherID:3,teacherName:"jill"},
{teacherID:1,teacherName:"john"},
{teacherID:2,teacherName:"joe"},
{teacherID:3,teacherName:"jill"},
]
Run Code Online (Sandbox Code Playgroud)
现在如何在对象teaherList中找到每个[teacherID:,teacherName: ]的频率
目前我在做的是,
let temp = []
_.each(teaherList, function(k){
temp.push(k.teacherID)
)
let count1 = countBy(temp);
Run Code Online (Sandbox Code Playgroud)
好吧,它给出了对象中教师发生的频率,但有一种更好,更高效的方法来完成这项任务
假设teaherList
是一个对象数组,这里的方法不需要依赖于库,并且一次创建输出对象(总迭代次数=数组长度),其中reduce
:
const teaherList = [
{teacherID:1,teacherName:"john"},
{teacherID:2,teacherName:"joe"},
{teacherID:3,teacherName:"jill"},
{teacherID:1,teacherName:"john"},
{teacherID:2,teacherName:"joe"},
{teacherID:3,teacherName:"jill"},
{teacherID:1,teacherName:"john"},
{teacherID:2,teacherName:"joe"},
{teacherID:3,teacherName:"jill"},
];
console.log(
teaherList.reduce((a, { teacherName }) => (
Object.assign(a, { [teacherName]: (a[teacherName] || 0) + 1 })
), {})
);
Run Code Online (Sandbox Code Playgroud)