JavaScript: Analyzing the occurrence rate of emojis within text

I'm currently working on a project to tally the frequency of emojis within a body of text. For instance:

"I adore 🚀🚀🚀 so much 😍 " -> [{🚀:3}, {😍:1}]

To accomplish this, I've developed a function that calculates the occurrence of characters in a block of text.

function getFrequency(string) {
    var freq = {};
    for (var i=0; i<string.length;i++) {
        var character = string.charAt(i);
        if (freq[character]) {
           freq[character]++;
        } else {
           freq[character] = 1;
        }
    }

    return freq;
};

source:

^While the above code functions well, it does not properly identify emoji characters:

{: 1,  : 3,  : 2}

Furthermore, I would like the output to be a list of json objects each containing one value, rather than a single lengthy json object.

Answer №1

To identify emojis in a string and count their frequencies, you can utilize the String.replace function with a unicode aware RegExp that captures symbols ranging from "Miscellaneous Symbols" to "Pictographs Transport and Map Symbols" (0x1F300 to 0x1F6FF):

let str = "I love 🚀🚀🚀 so much 😍 ";

let freq = {};
str.replace(/[\u{1F300}-\u{1F6FF}]/gu, char => freq[char] = (freq[char] || 0) + 1);

console.log(freq);

In case you want to avoid using RegExp or String.replace, another approach is to destructure the string into an array and then reduce it to compute the frequencies:

let str = "I love 🚀🚀🚀 so much 😍 ";

let freq = [...str].reduce((freq, char) => {
  if (char >= '\u{1F300}' && char < '\u{1F700}') freq[char] = (freq[char] || 0) + 1;
  return freq;
}, {});

console.log(freq);

Answer №2

charAt won't be useful in this situation. Instead, for...of will accurately parse the string into Unicode codepoints, even those in the astral plane. By using character.length, we can determine if a character is on the supplementary plane. If you want to specifically identify emojis, further refinement is required.

const input = "I love 🚀🚀🚀 so much 😍 ";
    
function getFrequency(string) {
  var freq = {};
  for (character of string) {
    if (character.length === 1) continue;
    if (freq[character]) {
      freq[character]++;
    } else {
      freq[character] = 1;
    }
  }
  return freq;
 };
 
 console.log(getFrequency(input));

If you need to convert the output into an array of single-valued objects, you can use the following function:

function breakProperties(obj) {
  return Object.keys(obj).map(function(key) {
    var result = {};
    result[key] = obj[key];
    return 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

Why does 1&&2&&3 result in 3? Could someone clarify this for me?

During a recent interview, I was presented with this question about JavaScript evaluation order. My understanding is that in JavaScript, evaluation proceeds from left to right. So would 1 && 2 result in false? I came across another discussion where it w ...

Comparing Fetch and Axios: Which is Better?

Currently delving into the realms of axios and the fetch API, I am experimenting with sending requests using both methods. Here is an example of a POST request using the fetch API: let response = await fetch('https://online.yoco.com/v1/charges/&ap ...

able to move through the content without displaying the scrollbar

I am looking to keep my content able to scroll, but I don't want the scrollbar to be visible. I have written my CSS like this: #content-three{ width:100%; height:100%; position:relative; overflow:hidden; } .block_s{ width:90%; ...

Unable to reach the prototype of the object

I am encountering an issue while attempting to access the object's prototype in a Node.js code. The objective is to send this object through an API so that users can utilize its methods. The problem lies in the fact that the returned object only inclu ...

When trying to link a Redis microservice with NestJS, the application becomes unresponsive

I am attempting to create a basic hybrid app following the guidance provided by Nest's documentation, but I have run into an issue where the app becomes unresponsive without any errors being thrown. main.ts import { NestFactory } from '@nestjs/c ...

Generate the Xpath for the mentioned href element to use with Selenium Webdriver

I need help creating the Xpath for a specific href element using Selenium webdriver with only IE browser. The HTML code I am working with is as follows: I am looking to find the Xpath for: . Can someone assist in generating the correct Xpath expression ...

Mapping a one-to-many relationship between Jersey web service and Hibernate

Encountering the 500 - Internal Server Error in POSTMAN while attempting to create a new user using Jersey rest service. Seeking guidance on properly loading and forming the JSON for hibernate one-to-many mappings. Utilizing jersey-media-moxy for JSON supp ...

Various relationships in Sails.js

Exploring associations in Sails.js beta (version 0.10.0-rc4) has been quite intriguing for me. My current challenge involves linking multiple databases to produce a unified result (utilizing sails-mysql). The association scheme I'm working with invo ...

Troubleshooting Route Rendering Issues with React Router Dom and Loading Components

I am currently developing a React project and focusing on the navbar element. As part of this, I am integrating the react-router-dom into the project. The <Route/> is nested within the <Routes/>, all encapsulated by the <BrowserRouter/>. ...

Include a nested array of objects in the path

I'm looking to enhance the data visualization process by adding a path to the data before plotting the chart. Is there a way to retrieve a specific object by key, even if it's deeply nested, using recursion? I've attempted to do so, but my c ...

Guide to modifying the column color in Chart.js

Link to my codepen project: Check it out here let ctx = document.getElementById('myChart').getContext('2d'); let chart = new Chart(ctx, { // Type of chart being created type: 'bar', // Data for the dataset data: { ...

Twilio Group MMS feature experiencing technical difficulties

I currently have a Twilio Trial account with an active number that supports SMS/MMS. My goal is to use this number for group MMS chats, but I am facing some challenges. After following a tutorial on Tut, I attempted to create a basic test using the provid ...

Creating an anonymous component in Vue.js involves enclosing the received slots (vnodes) within a wrapper component

Is there a way to wrap two specified named slots, slotOne and slotTwo, which are located in the child component at this.$scopedSlots.slotOne and this.$scopedSlots.slotTwo respectively? I would like to then conditionally render these slots (vnodes) as shown ...

Master the art of automatically formatting incorrect JSON using code in your Flutter project

I am currently facing an issue while trying to parse a json response. The problem lies in the presence of a trailing comma at the end of the response, causing errors during decoding. Is there a way to automatically format it from the code and remove the co ...

Obtaining a string value from a parallel array

Apologies for the very basic question, but I'm struggling with this. I have a word. Each letter of the word corresponds to a position in one array, and then returns the character at the same position from a parallel array (basic cipher). Here is my c ...

The ng-route feature seems to be malfunctioning and I am unable to identify the error, as no information is being displayed in the console

Here is the code in my boot.php file where I have set up the links <ul class="nav nav-pills nav-stacked"> <li role="presentation"><a href="#/valley">Valley</a></li> <li role="presentation"><a href="#/beach"> ...

Creating a box that is connected by lines using JSON data requires several steps. You

I am attempting to dynamically draw a line using the provided JSON data. I have heard that this can be easily achieved with flexbox. Important: I would greatly appreciate a solution involving flexbox This is what I hope to achieve: https://i.stack.imgu ...

What is the process for transferring `Parentobject1` to `childobject2` and `childobject3` in Three.js?

I have created two objects doubleSquare and doubleSquare1. I was expecting the output to be Double Line Square Object, but I have tried two different formats and have not achieved the desired output. Can someone please provide me with a solution? I have lo ...

Replicate the action of clicking on the download button in R

Is there a way to programmatically simulate clicking on the download button on the following website using R and download the TSV table? I have looked into methods such as Rselenium and PhantomJS, but they seem to be outdated now. I came across V8 as a po ...

Utilize the string module from a JavaScript file in your React or Next.js project

Within my project structure, I have a file named "test.js" located in the "/constants" directory. The content of this file is as follows: const test = "test!" export default test In another part of my project, specifically within the "/pages" folder, I w ...