Determine the frequency of a specific key in an array of objects

original array: ................

[
   {
    from: {_id: "60dd7c7950d9e01088e438e0"}
   },
   {
    from: {_id: "60dd7c7950d9e01088e438e0"}
   },
   {
    from: {_id: "60dd7e19e6b26621247a35cd"}
   }
]

A new array is created to count the instances of each _id and store it in messageCount .................

[
 {
  from: {_id: "60dd7c7950d9e01088e438e0"},
  messageCount: 2
 },
 {
  from: {_id: "60dd7e19e6b26621247a35cd"},
  messageCount: 1
 }
]

Answer №1

To tackle this issue, as suggested in the feedback, you can employ the reduce method.

const items = [
   {
    from: {_id: "60dd7c7950d9e01088e438e0"}
   },
   {
    from: {_id: "60dd7c7950d9e01088e438e0"}
   },
   {
    from: {_id: "60dd7e19e6b26621247a35cd"}
   }
];

/**
 * Function to extract the id from an item
 */
function getId(item){
    return item['from']['_id'];
}

// The initial value is an empty array passed as the second argument of the reduce function
// @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
const result = items.reduce(function (previous, next) {
    // Retrieve the id of the next item (or current item in the iteration)
    const id = getId(next);
    // Search for an existing item in the array
    // @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
    const index = previous.findIndex(item => id === getId(item));

    if (index !== -1) {
        // If there is already an item with the same id, increment the message count
        previous[index]['messageCount'] += 1;
    } else {
        // If there isn't an item, add a new one with a message count of 1
        previous.push({
            ...next,
            messageCount: 1,
        });
    }

    return previous;
}, []);

console.log(result);

References:

Answer №2

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);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the approach for utilizing Vue List Rendering with v-if to verify the presence of items within an array?

My current implementation utilizes v-if to conditionally display a list of cafes. However, I am interested in filtering the list based on whether a specific drink item is found in an array. For instance, I have a collection of cafes and I only want to dis ...

Creating a Validation Form using either PHP or JavaScript

I need to create a form with the following columns: fullname, email, mobile, and address. If the visitor fills out the mobile field, they should only be allowed to enter numbers. And if the visitor fills out the email field, they should only be allowed to ...

Utilizing Fullcalendar Qtip to display information on mouseover rather than utilizing the eventRender

I have a challenge with integrating Qtip to the eventMousever event instead of the eventRender event in fullcalendar. The main reason for this adjustment is due to the server hosting the data being located in another country, resulting in significant late ...

Unable to execute a JavaScript function when triggered from an HTML form

This is the code for a text conversion tool in HTML: <html> <head> <title> Text Conversion Tool </title> <script type="text/javascript"> function testResults(form) { var str = form.stringn.value; var strArray = str.split(" ...

The AJAX call returned undefined, leading to an error when trying to access the length property

I've scoured various resources to find a solution for this issue, but unfortunately, I haven't had any luck with implementing the code. The problem lies with my JSON parser function, which is designed to construct a table based on data received ...

Creating objects in Angular 2 through HTTP GET calls

Recently, I've delved into learning Angular 2. My current challenge involves making http get requests to retrieve data and then constructing objects from that data for later display using templates. If you believe my approach is incorrect, please feel ...

VueJS - Vuefire - Unexpected Error: document.onSnapshot is not a valid function

I'm currently working on integrating Vuefire into my project. I have been following the instructions provided on the Vuefire website, but I am encountering an error. db.js: import firebase from 'firebase/app' import 'firebase/firestore ...

In Angular, link a freshly loaded ".js" controller to a newly loaded "html" view following the bootstrapping process on ngRoutes

As a newcomer to Angular, I have been experimenting with loading dynamic views using ngRoutes (which is very cool) along with their respective .js controllers for added functionality. However, I am encountering difficulties in binding them together after b ...

Utilizing Multiple Checkboxes for Precision Search Refinement

Big thanks to Khalid Ali for the support provided up until now. I am currently working with an array of songs that each have descriptions, keywords, etc. I have a set of checkboxes that I want to use to refine a search. Essentially, if someone selects the ...

Having trouble getting autocomplete to work with JQuery UI?

Currently facing issues in implementing the Amazon and Wikipedia Autocomplete API. It seems that a different autocomplete service needs to be used based on the search parameter. Unfortunately, neither of the services work when adding "?search=5" for Wikipe ...

notify a designated channel when ready for launch

I'm currently attempting to figure out how to send a message to a channel when the Discord bot is launched. I've experimented with this code: client.on('message', (message) => { client.on('ready', () => { channel = cli ...

You are unable to select the element in IE if there is an image in the background

Apologies for coming back with the same question, as I realize now that I was not clear in my explanation yesterday. You can find the codepen here (please note that it may not open in IE8). My issue is with dragging the 'move-obj' element in IE b ...

Dissecting Distinct and Alphabetized Attributes in JSON/JavaScript

Below is a code snippet that retrieves and organizes a list of values from JSON data in alphanumeric order based on a specific key-value pair: var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 &a ...

The issue with EJS Header and Footer not showing up on the

I am currently building a basic todo list application using EJS. However, I am encountering an issue when running it. I would like to run app.js with the header and footer in EJS, but it seems that it is not recognizing the header despite using what I beli ...

Is it wise to question the validity of req.body in express.js?

https://expressjs.com/en/4x/api.html mentions It is crucial to validate all properties and values in the req.body object as they are derived from user input. Any operation performed on this object should be validated to prevent security risks. For instan ...

Update settings when starting with chromedriver

I am currently using webdriver (), standalone selenium, and mocha for writing my test cases. These test cases are specifically designed for Chrome, so I rely on chromedriver for execution. However, when launching the browser, I need to ensure that the "to ...

Tips for distinguishing individual rows within a table that includes rowspans?

My Vue application calculates a table with rowspans by using an algorithm based on a configuration file. This allows the application to render columns (and maintain their order) dynamically, depending on the calculated result. For example, see the code sn ...

Using Ajax, the script triggers calls upon detecting keyup events on various input fields, each

I'm encountering issues while attempting to solve this logic puzzle. The page contains multiple fields and the goal is to store the input values in the database when the user finishes typing. Here's the code snippet: var debounce = null; ...

jQuery Plugin - iDisplayLength Feature

I am currently using DataTables version 1.10.10 and I am looking to customize the main plugin Javascript in order to change the iDisplayLength value to -1. This adjustment will result in displaying "All" by default on all data tables, allowing users to fil ...

What is the reason for the find() method not displaying the most recent data from a MongoDB database in an Express.js application?

Upon calling the app.post('/form-submit', funtion(req, res)) method, my expectation is for it to first save the data using save(). This works fine, but then when I call the find() method, it shows all the data from the mongoDB database except for ...