I'm learning javascript and I have some problems. I would like to iterate an array of objects but with a few "options":
expected result :
received 1
missed 2
dialed 3
I know how to iterate a array of objects and use .length
to display the quantity of each item but I don't know iterate + display quantity + remove duplicates... Can you help me ?
const calls = [
{
type: "missed",
date: "xx-xx-xx"
},
{
type: "received",
date: "xx-xx-xx"
},
{
type: "dialed",
date: "xx-xx-xx"
},
{
type: "missed",
date: "xx-xx-xx"
},
{
type: "dialed",
date: "xx-xx-xx"
},
{
type: "dialed",
date: "xx-xx-xx"
}
];
A good way to group items is with reduce (it’s also flexible, so if you add another type it works no problem):
const calls = [{
type: "missed",
date: "xx-xx-xx"
},
{
type: "received",
date: "xx-xx-xx"
},
{
type: "dialed",
date: "xx-xx-xx"
},
{
type: "missed",
date: "xx-xx-xx"
},
{
type: "dialed",
date: "xx-xx-xx"
},
{
type: "dialed",
date: "xx-xx-xx"
}
];
const output = calls.reduce((aggObj, item) => {
if(!aggObj[item.type]){
aggObj[item.type] = 0
}
aggObj[item.type] += 1;
return aggObj;
}, {});
//output as object:
console.log(output);
//output as array:
const outArr = Object.entries(output);
console.log(outArr);
//output as strings:
outArr.forEach(([k,v]) => console.log(k,v));
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments