Is there a way for me to calculate the number of characters in a word that is part of

I have this array ["academy"] and I need to count the characters in the string within the array.

The expected output should look like this:

a:2
c:1
d:1
e:1
m:1
y:1

To achieve this, I attempted using two for loops as shown below:

function sumChar(arr){
    let alph = "abcdefghijklmnopqrstuvxyz";
    let count = 0;
    for (const iterator of arr) {
        for(let i=0; i<alph.length; i++){
            if(iterator.charAt(i) == alph[i]){
                count++;
                console.log(`${iterator[i]} : ${count}`);
                count = 0;
            }
        }
    }
}
console.log(sumChar(["abdulloh"]));

However, the function is not producing the correct output. Instead, it gives me:

a : 1
b : 1
h : 1
undefined

Answer №1

One effective approach is to use the [...new Set(word.split(''))] method, which generates an array of unique letters by removing duplicates. The .map function then loops through each letter in this array and calculates how many times it appears in the word with

({ [m]: word.split(m).length - 1 })
, where the letter is set as the object key and its frequency is determined using word.split(m).length - 1.

const countLetters = word => (
  [...new Set(word.split(''))].map(m => ({
    [m]: word.split(m).length - 1
  })))

console.log(countLetters("academy"))

Answer №2

A unique approach to finding occurrences is by using regex. I have created a method that specifically checks for characters in a given string. Hopefully, this code snippet proves to be useful.

word: string = 'abcdefghijklkmnopqrstuvwxyzgg';
charsArrayWithCount = {};
CheckWordCount(): void {
    for(var i = 0;i < this.word.length; i++){
        if(this.charsArrayWithCount[this.word[i]] === undefined){
            this.charsArrayWithCount[this.word[i]] = this.charCount(this.word, this.word[i]);
        }
    }
    console.log(this.charsArrayWithCount);
}
charCount(string, char) {
    let expression = new RegExp(char, "g");
    return string.match(expression).length;
}

Answer №3

To fulfill this requirement, you can make use of the Array.reduce() method in JavaScript.

Check out a live demonstration below:

const arr = ["awesome"];

const result = arr.map(word => {
  return word.split('').reduce((obj, cur) => {
    obj[cur] = obj[cur] ? obj[cur] + 1 : 1;
    return obj;
  }, {});
});

console.log(result);

Answer №4

This is my take on the simplest solution:

let word = 'academy';

let letterFrequency = {};

word.split('').forEach(letter => letterFrequency[letter] = (letterFrequency[letter] ?? 0) + 1);

console.log(letterFrequency);

Answer №5

const words = ["academy"];
let characterCount = {};
for (let index = 0; index < words.length; index++) {
  let currentWord = words[index];
  for (let char of currentWord) {
    if (char !== " ") {
      characterCount[char] = currentWord.split("").filter((x) => x == char).length;
    }
  }
}

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

Having trouble selecting an element by name that contains a specific string followed by [..] using jQuery

I have elements with names like kra[0][category], kra[1][category], and so on. However, I am facing difficulties in selecting these elements by name. Here is my jQuery code: $("[name=kra[0][category]]").prop("disabled", true); ...

Determine value by correlating the JSON key and value with another JSON file using JavaScript/Node.js

Attempting to set a json value by comparing deeply nested json objects The initial json object result appears as follows when logged: result { "computer": { "en": { "4gSSbjCFEorYXqrgDIP2FA": { "galle ...

Encountering NaN while trying to retrieve the duration in JavaScript

I'm having an issue retrieving the duration of an mp4 video file when the HTML document loads. Here's my code: (function ($, root, undefined) { $(function () { 'use strict'; $(document).ready(function() { ...

By implementing JavaScript formulas into a CSV file for importing into Google Sheets, the outcome is the creation of numerous columns

I have been struggling to insert the following formula into a single column in Google Sheets using JavaScript, but it keeps appearing in different columns due to the presence of commas. =IF(A2="VALID", B2, 0) Currently, I am utilizing the code ...

invoke a managed bean to execute JavaScript code

I am facing an issue while trying to clear a hidden form value in a JSF page from a managed bean class. I tried calling a method where I used the following code snippet to call JavaScript, but unfortunately it throws a java.lang.NullPointerException. The c ...

Enhancing ReactJS functionality by incorporating custom logic prior to resolving promises

In one of my components, there is a function as follows: this.props.firebase.getDropSites("123456").then(data => { console.log(data); }); This function in turn calls the following method from my utilities class: getDropSites(dropSiteId) { return th ...

Implementing JavaScript to display specific content when a list is devoid of any items

Currently, I am in the process of developing a basic contact list web application where the contacts are listed within li elements. My aim is to adjust the visibility of the text in the p#no-contacts element based on whether the containing ul has any child ...

Would it be unwise to send an AJAX post request every two seconds?

Is it frowned upon or risky to use an AJAX $.post call (with jQuery) to a php file in order to update a specific parameter or number? $.post(file.php, {var:var}, function(data){ // do something }, json); In this scenario, only one user on a single page w ...

How can I send data with ajax and then navigate to the page with the posted information?

I'm facing an issue where I need to send 2 Ajax requests simultaneously. The challenge is posting data to one file, receiving a response, and then posting to another page with the intention of accessing the posted values using $_post on the next page ...

What is the best way to incorporate a button for toggling CSS animations?

I need help adding a button to toggle the animation on this JSFiddle. I tried adding the code below but can't seem to start and stop the animation. body .a [class^="b"] { width: 200px; height: 142.8571428571px; margin: 0 auto; ...

Encountering a POST 504 error while attempting to proxy an Angular application to a Node server

error message: Failed to connect to http://localhost:4200/api/user/login with a 504 Gateway Timeout error. Encountered this issue while attempting to set up a login feature in my Angular application and establish communication with the Express backend. Th ...

``Implementing a method to save the output of an asynchronous request in a global variable for future manipulation

It's been a week and I still can't figure this out. Being new to front-end development, I'm struggling with storing the response from subscribe in a global variable for future use. ngOnInit(): void { this.http.get<APIResponse>('ur ...

Display dynamic elements based on names in a React application

Can you help me with setting a personalized tag in React? Every import is a JSX Element. Consider GitHub, which is imported from a file structured like this: import React from 'react'; const GitHub = () => ( <svg role="img" viewBox="0 ...

Unexpected results are being produced by Moment Timezone

It seems like I might be making a mistake here. Currently, the time in Lisbon is 12:27 PM However, the code snippet below returns 14:27 (EU central time) const time = moment.tz("Europe/Lisbon") const timeZone = "Europe/Lisbon" co ...

How can Angular 7 incorporate inline JavaScript scripts in a component?

I am facing an issue while trying to integrate the places.js library into my Angular 7 project. I have added the necessary script in my 'index.html' file as follows: <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-prot ...

JSON Array Position Sequence

I have a system that takes input in the form of lines of text stored as an array, for example: array[123,556,"test",0,0]. By using val().split('\n'), I am able to add each new line to the array so that each line index is incremented by 1. He ...

Preventing requests from being executed concurrently in PM2

In my Express application, I have set up two endpoints. One for checking if the server is up and running, and another for simulating a blocking operation. app.use('/status', (req, res) => { res.sendStatus(200); }); app.use('/p', ...

Having trouble with Angular ngRoute functionality?

I'm currently working on configuring a basic Angular app. Here is my main HTML: <html ng-app="CostumerApp"> <head> <title> Customers </title> <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstr ...

Setting up a new folder in the internal storage within a React Native Expo environment

In my React Native Expo project, I am utilizing two functions to store data in a JSON file and then save the file to internal storage. However, the code currently asks for permission to store inside a chosen folder, but does not create the "ProjectName" fo ...

What is the best way to trigger my web scraper within an express route?

Within my Nodejs server's root directory, I have implemented a web scraper using needle to handle the HTTP requests for retrieving HTML data. This scraper returns an Array of data upon completion. In addition, there is an index.js file containing expr ...