Alphabet Frequency Chart: Counting the occurrences of each letter in a given string (even if it is 0)

I have developed a function that generates an array showing the frequency of each letter in the alphabet (a-z) within a given string, including 0 occurrences. The array consists of 26 numbers representing each letter of the alphabet. Here is the function I have created so far. While it functions correctly, I believe there may be a more streamlined approach to improve this solution.

export function generateMap(text){

 const text_arr = text.toLowerCase().split('');
 const valid_char = 'abcdefghijklmnopqrstuvwxyz'.split('')

 const map = {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0, 'g': 0, 'h': 0, 'i': 0, 'j': 0, 'k': 0, 'l': 0, 'm': 0, 'n': 0, 'o': 0, 'p': 0, 'q': 0, 'r': 0, 's': 0, 't': 0, 'u': 0, 'v': 0, 'w': 0, 'x': 0, 'y': 0, 'z': 0}


 text_arr.forEach(char => {
   if(valid_char.indexOf(char) > -1) map[char]++
 })

 return Object.values(map)

}

Answer №1

When it comes to utilizing ES6, one innovative approach is extending the Map object with additional features for a more seamless process. This involves implementing an update() function for semantic incrementation and a get() function that provides a default value (such as 0) if a key does not currently exist in the map:

class DefaultMap extends Map {
  constructor (defaultValue, iterable = []) {
    super(iterable)
    this.default = defaultValue
  }

  get (key) {
    if (this.has(key)) {
      return super.get(key)
    }

    return this.default
  }

  update (key, fn) {
    this.set(key, fn(this.get(key)))
  }
}

const initialCharCode = 'a'.charCodeAt(0)

// create valid characters based on the ASCII table for characters a-z
const validChars = Array.from(
  {length: 26},
  (value, index) => String.fromCharCode(index + initialCharCode)
)

function generateMap (text) {
  const chars = text.replace(/[^a-z]/gi, '').toLowerCase().split('')
  const map = new DefaultMap(0)

  chars.forEach(char => map.update(char, count => count + 1))

  return validChars.map(validChar => map.get(validChar))
}

console.log(generateMap('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'))

In addition, the validChars are defined only once outside the generateMap() function to avoid redundant declarations. It is also beneficial to retrieve our array by mapping validChars rather than using Object.values() on the map, ensuring that the iteration order adheres to specifications rather than implementation-specific behavior.

Answer №2

Update:

function createCharacterMap(input){

    let inputArray = input.toLowerCase().split('').sort();

    const validCharacters = 'abcdefghijklmnopqrstuvwxyz'.split('').sort();
    const charMap = {};

    validCharacters.forEach(character => {
        let count = inputArray.lastIndexOf(character) + 1;
        inputArray = inputArray.slice(count);
        charMap[character] = count;
    });

    return Object.values(charMap)
}

The sort() function on validCharacters is crucial for proper execution.

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

Fetch data dynamically upon scrolling using an AJAX request

Instead of making an ajax call to load data, I want to do it on scroll. Here is the code I have: $.ajax({ type: 'GET', url: url, data: { get_param: 'value' }, dataType: ' ...

Changing images dynamically in tinymce using JavaScript

When using the tinymce editor, I attempt to modify my images. I currently have an image within it and I am trying to dynamically change the path of this image with: tinymce.activeEditor.selection.getNode().src = '/my/path/' Surprisingly, this m ...

I'm looking to combine multiple RSS feeds into a single feed, then transform the combined feed into JSON data using JavaScript. How can I achieve this?

I have been experimenting with merging multiple RSS feeds into one and converting it to JSON format. For combining the feeds, I utilized the following package: rss-combiner Below is the code snippet that successfully combines the RSS feeds: var RSSCombin ...

What is the best way to trigger a function upon the completion of an interpolation using tween.js?

I have an array named mesh with 10 individual meshes stored in it. console.log(mesh.length) // -> 10; My goal is to animate a scale change for each mesh by assigning a new scale value to them. To achieve this, I utilize a for loop in combination with ...

The Vue.js updated hook causing unnecessary page rerenders even when there are no changes in the state

Seeking to retrieve data from an api and utilize updated() to trigger a rerender upon a change in the state that stores the fetch url. However, encountering an issue where the updated hook continues to render even when there is no alteration in the state. ...

Error: Unexpected syntax error in JSON parsing after importing PHP file

Encountered an unexpected error: Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data site:stackoverflow.com, which is appearing in the Firefox debug console. On my website, I have a form that triggers this function o ...

Exploring logfile usage in JavaScript. What is the best way to structure the log?

Currently, I am developing a Python program that parses a file and records the changes made to it. However, I am facing a dilemma regarding the format in which this information should be saved for easy usage with JavaScript on the local machine. My objecti ...

Using the let keyword from another component within the main React application: Helpful tips and tricks

I'm new to React and I want to be able to use the formIsValid state from one component in my main App.js file. When formIsValid is false, I want the DeliveryNote component to be visible, but when it changes to true, I want to hide the DeliveryNote com ...

Detecting repeated property values within a collection of embedded objects

I am currently working with a JSON file that contains an array of nested objects and arrays to represent a shopping cart. My goal is to identify duplicate values and update the quantity of the item if duplicates exist, otherwise simply add the items to the ...

When trying to extract information from a v-for loop and pass it into a method, I keep

After sending an array of data objects into a child component via props, I proceeded to use a v-for loop to display the elements exactly how I intended: <div class="col-md-3" v-for="product in products" :key="product.id" v ...

Waiting for a promise in node.js that is not yet resolved

I have an async function in my "app.js" that is waiting for a connection to be ready from the imported connection.js file. I am struggling with getting app.js to work correctly with the "await". I am unable to add an export in the 'on' function ...

Having trouble with CSS and javascript files not resolving after moving app to a new Windows 7 development machine

I have recently migrated my ASP.Net 3.5 web site from my old XP sp3 machine to a new Win 7 64-bit dev machine. The web application utilizes Master Pages, App_Themes with style sheets and images, as well as an image folder located off the main root. Additio ...

What is the best way to retrieve the items stored within the array generated by a JavaScript function?

This particular function is responsible for calling a PHP script that outputs JSON data. It then iterates through the JSON object, creates a new object, and adds this new object to an array which is ultimately returned by the function. function getTestQues ...

Is there a way to set the canvas size to match the exact window size in pixels without being affected by the browser's zoom factor?

I'm currently developing a website called sphere.mars2540.com. Is there a way in JavaScript or CSS to maintain a fixed canvas size regardless of the zoom level of the page, ensuring it always aligns with the actual pixels on the screen (even with 4k ...

Inject the content loaded from the server into a div element, and insert that div at the

I am trying to insert the div(#loadmore) element inside the div(#boxchatting) element when the content from "result.php" is loaded into div(#boxchatting). Here is the code I used: $('#loadmore').prependTo('#boxchatting'); $('#boxc ...

If you're not utilizing v-model.lazy, Vue3 Cleave js may encounter functionality issues

I am currently experimenting with cleavejs to format the thousand separator in my input numbers. I've noticed a strange behavior where if I input 1000.123, it displays as 1,000.12 which is the correct format. However, the v-model value remains as 1000 ...

What is the best method for adjusting the text size within a doughnut chart using react-chartjs-2?

Is there a way to adjust the text size within the doughnut chart using react-chartjs-2? I find that the center text appears too small. https://i.stack.imgur.com/QsI0V.png import React, {Fragment} from 'react'; import Chart from 'chart.js&a ...

Locate and retrieve user data from MongoDB

Let me provide some context. I am transmitting a post along with the username and what he shared with me is shown in the log. console.log(req.body.username); // 'username' My question is, how can I utilize mongodb to locate and display a user w ...

Unexpected behavior: custom event firing multiple times despite being emitted only once

I am utilizing the ws module for incorporating web sockets functionality. An event named newmessage seems to be triggering multiple times in correlation with the number of active sockets connected to the web-socket-server. The scenario puzzled me initiall ...

What is the best way to limit the number of items shown in a cart dropdown using JavaScript

I have a shopping cart feature added to my ecommerce web app. Within the header, there is an icon of a cart. When clicked, a dropdown appears showing the items added to the cart. However, if I have 10 items in the cart, the dropdown becomes too lengthy to ...