Tally up identical words without considering differences in capitalization or extra spaces

Let's take an example with different variations of the word "themselves" like "themselves", "Themselves", or " THEMSelveS " (notice the leading and trailing spaces), all should be considered as one count for themselves: 3

This is my code:

const { readFile, readFileSync } = require('fs');


let file = 'C:\Users\eeroj\source\repos\Nodejs\pish\pish';


function countRepeatedWords(sentence) {
let words = sentence.split(" ");
let wordMap = {};

for (let i = 0; i < words.length; i++) {
    let currentWordCount = wordMap[words[i]];
    let count = currentWordCount ? currentWordCount : 0;
    wordMap[words[i]] = count + 1;
}

const sortedEntries = Object.entries(wordMap).sort(([a,], [b,]) => a.localeCompare(b));
const sortedWordMap = Object.fromEntries(sortedEntries);


return sortedWordMap
return wordMap;

}

words = readFileSync(file).toString();
console.log(countRepeatedWords(words));

Answer №1

To convert all words to lowercase, you can utilize the toLowerCase() function:

let words = sentence.split(" ");
let wordMap = {};

for (let i = 0; i < words.length; i++) {
    const key = words[i].toLowerCase();
    let currentWordCount = wordMap[key];
    let count = currentWordCount ? currentWordCount : 0;
    wordMap[key] = count + 1;
}

Another suggestion would be to implement a for of loop, eliminate empty cells, declare everything as const, and make use of Nullish coalescing:

const words = sentence.split(" ").filter(word => word); // excludes empty words
const wordMap = {};

for (let word of words) {
    const key = word.toLowerCase();
    const currentWordCount = wordMap[key];
    wordMap[key] = (currentWordCount ?? 0) + 1;
}

Answer №2

Transform all words to lowercase using the functions toLowerCase() and remove extra spaces with trim().

for (let word of words) {
    word = word.trim().toLowerCase();
    wordMap[word] = (wordMap[word] ?? 0) + 1;
}

Additional Information:

  • If you prefer, you can split the sentence by one or more spaces instead of using .trim(): let words = sentence.split(/ +/).
  • Consider utilizing a Map structure instead of an object, or use Object.create(null) to avoid mixing your data with built-in properties.

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

Tips for preventing special characters from being entered into a Kendo grid input column

Is there a way to prevent users from entering special characters into the description column of my Kendo grid? The column field setup is as follows: { field : "myDesc", width : 200, title : "My Description"} I have attempted the following approach so far ...

Node.JS program unexpectedly logging MySQL results to console and exhibiting erratic behavior

Recently, I encountered a peculiar error while working with Node.JS MySQL. Strangely, I noticed that a result was being logged in the console without any corresponding code line instructing it to do so. Even more baffling was the fact that when I intention ...

Node.js UDP broadcast to subnet not working properly in Linux

Here is a simplified Node JavaScript code snippet for testing purposes. Click here to view the code on GitHub This code creates a socket for each interface address, calculates the subnet broadcast address, and then sends data every second for 4 seconds t ...

Nested function and the process of breaking out of the parent function

Is it possible to exit out of the main/parent function when I am in a function that was called from inside another function? For example: function(firstFunction(){ //stuff secondFunction() // code continuation if second function doesn't ...

Firebase Error: Trying to access properties of null object (indexOf)

Whenever I try to console.log(docSnap), a Firebase error shows up as seen in the image below. Despite attempting various solutions, none have proved effective. https://i.sstatic.net/9R4vE.png useEffect(() => { if (folderId === null) { ...

NodeJS Express REST API fails to fetch data in GET request

As I work on developing a REST API using NodeJS and Express, I have set up routes for handling "offers". However, when attempting to send a GET request, I receive an empty response along with a 200 status code. Here is the snippet from routes.js: route ...

What is the most efficient way to dynamically alter the position of a div element within an HTML document using

In a scenario where a parent div contains multiple child divs, it is required that one particular child div named .div_object_last always stays at the end. Below is an example setup : HTML <div class="div_parent"> <div class="div_object"> ...

Improve loading speed of thumbnail and full images in HTML

I'm struggling with slow loading images on my blog website. Can anyone help me figure out how to improve loading speed and: Is it possible to use a separate thumbnail image that is smaller in size instead of the full image for both thumbnails and th ...

modal failing to populate values within control elements in modal

Encountering an issue where the code is calling a Modal, but upon loading it fails to populate the controls with values sent into the JavaScript. No errors are thrown, yet all controls remain empty. As a newcomer to AJAX and JavaScript, I suspect there mig ...

What is the best way to initiate WebXR from an iframe in a Next.js environment?

I am currently working on a Next.js app: https://codesandbox.io/s/next-js-forked-6fgnr7?file=/index.tsx I have implemented the functionality for it to open WebXR on Android Chrome when clicking on the AR button located at the bottom left ("in AR betracht ...

Unable to retrieve value - angularJS

An AngularJS application has been developed to dynamically display specific values in an HTML table. The table consists of six columns, where three (Work Name, Team Name, Place Name) are fixed statically, and the remaining three columns (Service One, Servi ...

Displaying elements of array in Pug template is a key task for

As a newcomer to the Jade/Pug template engine used in Express, I am faced with a challenge. I need to display the name property of each object within an associative array that is passed as a parameter to my pug template from an express route module. I hav ...

Getting the location of a mouse click and adding tags (marks) on an image: a simple guide

Is there a way to incorporate images with tagged marks similar to Facebook's image tagging feature? How can I retrieve the X and Y coordinates of tags on the image itself (not the screen) and display them in a responsive manner? ...

Utilizing jQuery to efficiently chunk JSON data through AJAX calls

Is there a way to efficiently handle the retrieval of large amounts of JSON data through an ajax request? I am looking for a jQuery or JavaScript function that can assist with "chunking" the data. For example, I would like the ability to continuously rece ...

stop the page from refreshing when clicking on the map area

http://jsbin.com/iTeNiJIt/1/edit?output I currently have multiple map areas on my webpage. When a user clicks on any of these areas, I want to create an animation without refreshing the page. However, I am facing an issue where the page refreshes every ti ...

Issue with Axios Get method: Data not displaying in table

Can someone assist me with displaying JSON data on my website? I am using an API with a security token, and everything seems to be working fine until I try to display the JSON data on my page. I can see the data in my console, but not on the actual page. ...

jQuery struggles to process large response

I am currently developing an application that sends requests to a URL and parses the table found in the HTML response using jQuery. While this method works well for smaller amounts of HTML code, it runs into issues with larger datasets. The problem arises ...

Combining React-Redux and Bootstrap: A sophisticated modal feature

Struggling with the distinction between components and containers when using Bootstrap's modal in React-Redux. Instead of repetitively creating modals, I aim to develop a React Component that encompasses a modal template. For clarification, here&apo ...

Utilizing interface in NestJS for validating incoming request parameters

My goal is to utilize the interface provided by class-validator in order to validate a specific field in the incoming request body. Here's the interface structure: export enum Fields { Full_Stack_Dev = 'full stack dev', Frontend_Dev = &a ...

What is the best way to exclude HTML tags from the innerHTML attribute?

Currently, I am in the process of developing a messenger application and facing an issue where my messages are not ignoring HTML tags. This is happening because I directly paste the input text into the innerHTML of the message. The code snippet responsible ...