Utilizing array methods, I incorporated a combination of .forEach
loop along with the .reduce
method ... Additionally, to determine the frequency of occurrences, I devised a straightforward array method ...
const array = [
{
from: {_id: "60dd7c7950d9e01088e438e0"}
},
{
from: {_id: "60dd7c7950d9e01088e438e0"}
},
{
from: {_id: "60dd7e19e6b26621247a35cd"}
}
];
/*
Formulating an array method capable of identifying the number of times the specified item appears within the array
*/
Array.prototype.getItemCount = function(item) {
let counts = {};
for (let i = 0; i < this.length; i++) {
let num = this[i];
counts[num] = counts[num] ? counts[num]+1: 1;
}
return counts[item] || 0;
};
let result = [];
// Collating all ids and storing them in a constant using the array.reduce method
const allIds = array.reduce((acc,item)=> acc.concat(item.from._id),[]);
// Employing a forEach loop coupled with a ternary operator to filter out unique ids (conditions)
let filtered_id = [];
allIds.forEach((id)=> {
!filtered_id.includes(id) ? filtered_id.push(id) : null;
});
// Eventually, compiling all the pertinent data into the designated result!
filtered_id.forEach(id =>{
result.push({
from: { _id: id },
messageCount : allIds.getItemCount(id)
});
});
console.log(result);