Home > Net >  How to count the properties of an array of objects in JavaScript
How to count the properties of an array of objects in JavaScript

Time:11-08

var employees = [
{ name: "Josh", title: "receptionist" },
{ name: "Naila", title: "receptionist" },
{ name: "Tom", title: "doctor" },
{ name: "Becky", title: "doctor" }
];

For example on this one I would like to return
{
    'doctor':2,
    'receptionist':2
}

This is what I have tried:

const convert = (employees) => {
    const res = {};
    employees.forEach((employee) => {
        const key = `${employee.title}${employee["doctor-receptionist"]}`;
            if (!res[key]) {
                res[key] = {...employee, count: 0 };
            };
            res[key].count  = 1;
        });
    return Object.values(res);
};
console.log(convert(employees));

It returns the name of the employees, which I did not want. I also thought about creating arrays for each kind of job title and filtering each employee from the employee array, and pushing them to their respective arrays. But I feel like there must be an easier way.

CodePudding user response:

Just using reduce() can do it

var employees = [
  { name: "Josh", title: "receptionist" },
  { name: "Naila", title: "receptionist" },
  { name: "Tom", title: "doctor" },
  { name: "Becky", title: "doctor" }
]; 

let result = employees.reduce((a,c) =>{
   a[c.title] = a[c.title] ? a[c.title]   1 : 1
  return a
},{})

console.log(result)

CodePudding user response:

The reduce iterator was built for this kind of thing. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

I also employ Object.values() since the way I am using reduce is to create an object to easily keep track of the data along the way. The object.values helps distill that into an array when done.

const employees = [
  { name: "Josh", title: "receptionist" },
  { name: "Naila", title: "receptionist" },
  { name: "Tom", title: "doctor" },
  { name: "Becky", title: "doctor" }];
  
const reduced = Object.values(employees.reduce((b,a) => {
if (!b[a.title]) b[a.title] = {title: a.title, count: 1}
else b[a.title].count  ;
return b
},{}))

console.log(reduced);
  

CodePudding user response:

you can try this on your code

const employees = [
    { name: "Josh", title: "receptionist" },
    { name: "Naila", title: "receptionist" },
    { name: "Tom", title: "doctor" },
    { name: "Becky", title: "doctor" }
]  


const sumReceptionist = employees.filter((item)=>{
    return item.title === 'receptionist'
}).length
const sumDoctor = employees.filter((item)=>{
    return item.title === 'doctor'
}).length

let total =
    {
        receptionist: sumReceptionist,
        doctor: sumDoctor
    }

console.log(total)

CodePudding user response:

I think this is what you're trying to do. You want the total of the positions from the employee list?

const Employees = [{
    name: "Josh",
    title: "receptionist"
  },
  {
    name: "Naila",
    title: "receptionist"
  },
  {
    name: "Tom",
    title: "doctor"
  },
  {
    name: "Becky",
    title: "doctor"
  },
  {
    name: "Chad",
    title: "doctor"
  },
  {
    name: "Cindy",
    title: "nurse"
  }
];

// A forEach won't return an object or array, so we create one to modify within it
const PositionTotals = {};
Employees.forEach(employee => {
  // Check if property exists. If not, create it and add one to it before continuing loop
  if (!PositionTotals.hasOwnProperty(employee.title))
    return PositionTotals[employee.title] = 1;
  PositionTotals[employee.title]  ;
})

console.log(PositionTotals);
$('#PositionTotals').html(JSON.stringify(PositionTotals, null, '\t'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<pre id="PositionTotals"></pre>

CodePudding user response:

Array#reduce is the way to go:

const employees = [ { name: "Josh", title: "receptionist" }, { name: "Naila", title: "receptionist" }, { name: "Tom", title: "doctor" }, { name: "Becky", title: "doctor" } ],

    summary = employees
        .reduce((acc,{title}) => ({...acc,[title]:(acc[title] || 0)   1}),{});
        
console.log( summary );

  • Related