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

I'm having trouble with the routing of a Node.js REST API built with Express and Mongoose

I am currently in the process of constructing a RESTful webservice by following a tutorial that can be found at: However, I have encountered an issue where it is returning a CANNOT GET/ reports error. Despite my efforts to troubleshoot and rectify the pro ...

A comprehensive guide to using Reactive Forms in Angular

I need help understanding how FormGroup, FormControl, FormArray work in Angular. The error message I'm encountering is: Type '{ question: FormControl; multi: true; choices: FormArray; }' is not assignable to type 'AbstractControl' ...

Utilizing the power of combined variables in Javascript

Is there a method to incorporate variables in each loop of a javascript loop? For instance, if I were to insert this code into a loop if (e1) {item_text += '{id:"' + id[1] + '",lvl:' + e1lvl + '},<wbr>'} if (e2) {item_ ...

Error: An issue occurred with the tasks in the Gruntfile.js file

pm WARN EPACKAGEJSON <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="74041506001a1106041b0600151834445a445a44">[email protected]</a> No description npm WARN EPACKAGEJSON <a href="/cdn-cgi/l/email-protection" ...

The div is not displaying the conditional styling as expected

I need help with mapping an array of cards wrapped in a div. I want the first, second, second-to-last, and last divs to go on a new line or take up the entire row. My project is in Vue3 and I'm using the PrimeVue component library. <div class=" ...

Submitting an extremely large string to an Express server using JS

How can a large String be efficiently sent to a Node.js Express server? On my webpage, I am using Codemirror to load files from an Express server into the editor. However, what is the most effective method for sending "the file" (which is actually a bi ...

Searching for a name in JSON or array data using jQuery can be accomplished by utilizing various methods and functions available

Having trouble searching data from an array in jQuery. When I input Wayfarer as the value for the src_keyword variable, it returns relevant data. PROBLEM The issue arises when I input Wayfarer Bag as the value for the src_keyword variable. It returns em ...

What is the best way to create transitions for item entry and exit in ReactJS without relying on external libraries?

I am looking to create an animation for a toast notification that appears when a user clicks on a button, all without the use of external libraries. The animation successfully triggers when the toast enters the screen upon clicking the button. However, I e ...

Personalizing MaterialUI's autocomplete functionality

Trying to implement the material-UI Autocomplete component in my react app and looking for a way to display a div when hovering over an option from the list, similar to what is shown in this reference image. View example If anyone has any tips or suggest ...

Tips on resetting the position of a div after filtering out N other divs

Check out this code snippet. HTML Code: X.html <input type="text" id="search-criteria"/> <input type="button" id="search" value="search"/> <div class="col-sm-3"> <div class="misc"> <div class="box box-info"> ...

Navigate through set of Mongoose information

I have a challenge where I need to retrieve an array of data from Mongoose, iterate through the array, and add an object to my Three.js scene for each item in the array. However, when I try to render the scene in the browser, I encounter an error that say ...

``Is there a way to align components with the same width side by side horizontally

I have a situation where I need to align three components, a radio button and two select fields, on the same row within a container. Currently, they are displaying on separate rows but I want them to be in three columns on a single line. I tried following ...

Tips for creating a responsive carousel slider for images

No matter how much I've tried, I can't seem to find a solution on how to make my image responsive along with the caption. Below is my HTML code: <section id="banner"> <div class="banner-bg"> <div class="banner-bg-item ...

What is the correct way to generate a normal map using THREE.js?

Experimenting with the Normal map Ninja demo, I attempted to apply it to a cube in my scene using the most recent version of Three.js from the development branch: // Setting up common material parameters var ambient = 0x050505, diffuse = 0x331100, specul ...

Employing jQuery to add an element as a sibling rather than a child node

I'm having trouble finding the specific functionality I need. My goal is to add sibling DOM elements to a disconnected node. From what I gather, it should be possible with either .after() or .add(), but for some reason both methods are not working as ...

Steps to installing npm on Ubuntu without root access:1. First, download

I have successfully installed node in a custom directory within my home folder called "local" following the instructions provided here: https://gist.github.com/isaacs/579814 Here is the output: Creating ./icu_config.gypi * Utilizing ICU in deps/icu-sma ...

Drag the label into the designated paragraph to copy the text. Click on the specific point to transfer the text

How can I copy the text from a label to a specific point by dragging it? <label id="text_to_be_copied" > i am a student </label> Below is a paragraph where I want to paste the copied text: <p> this is the content where I want to copy t ...

The chart refreshes whenever there is a change in the component's state

Whenever I click the button to use the changeState method, the state changes and the MoreInfo component appears. However, the chart is being drawn again as shown in this GIF: Below is the code snippet: import React from 'react' import './Ho ...

Is there anyone who can assist me with the problem I'm facing where Javascript post call is sending a null value to my mongoDB

As a beginner in JS, NodeJS, and MongoDB, I decided to create a quiz website to sharpen my coding skills. However, I have encountered an issue while trying to send the username (string) and total marks (int) to MongoDB using the Post method. Surprisingly, ...

I'm encountering an error while attempting to parse the XML file

Need help with ajax call $j.ajax({ url: "http://www.earthtools.org/timezone/40.71417/-74.00639", dataType: "jsonp", complete: function(data){ console.log(data); } }); The URL returns XML, but I'm trying to use JSONP to avoid cross-site s ...