Search code examples
javascriptarraysobjectfrequencyfind-occurrences

finding the frequency of a key value pair in an object in javascript


imagine I have an object

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"},
]

now how do i find the frequency of each [teacherID:,teacherName:], in the object teaherList

currently how I am doing is,

let temp = []
_.each(teaherList, function(k){
   temp.push(k.teacherID)
)

let count1 = countBy(temp);

well it is giving the frequency of the occurrence of the teachers in the object but is there a better and performant way to do this task


Solution

  • Assuming teaherList is meant to be an array of objects, here's a method that doesn't require depending on a library, and also creates the output object in one go (total iterations = length of array), with 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 })
      ), {})
    );