What is the best way to find unique characters along with their frequency in JavaScript?

Can you help me adjust this code in order to receive the desired output: "T-1 r-1 a-1 e-1 "

(other characters are repeating. So no need to print the others)

function checkUniqueCharacters() {

    var uniqueChars = [];
    var count = 0;
    var fullName = "Trammell";
    var stringLength = fullName.length;

    for (var i = 0; i < stringLength; i++) {
        for (var j = 0; j < stringLength; j++) {
            var char1 = fullName.charAt(i);
            var char2 = fullName.charAt(j);

            if (char1 != char2) {
                uniqueChars[count] = char1;
                count++;
            }
        }

        count = 0;
    }
}

Answer №1

The solution to your problem involves counting the occurrences of each character in a given string and outputting those that occur only once.

var uniqueChars = [];
var testString = "Hello";

for (var i = 0; i < testString.length; i++)
{
    var character = testString[i];
    if (!(character in uniqueChars))
    {
        uniqueChars[character] = 1;
    }
    else
    {
        uniqueChars[character] = uniqueChars[character] + 1;
    }
}

var result = "";
for (var character in uniqueChars)
{
    if (uniqueChars[character] == 1)
    {
        result += character + "-" + uniqueChars[character] + " ";
    }
}

alert(result);

When executed, this code will display the following output:

H-1 e-1

Answer №2

This approach gets the job done, but there may be more efficient methods available!

let input = "sample input";
let charArray = [];
let output = "";

for (let i = 0; i < input.length; i++){
    let charObj = {"Char": input.charAt(i), "Passed": false};   
    charArray.push(charObj);
}

for (let i = 0; i < charArray.length; i++){
    if (!charArray[i].Passed && charArray[i].Char !== " "){
        let count = countOccurrences(input, charArray[i].Char);
        if (count === 1){
            output += charArray[i].Char + "-" + count + " ";
        }
        charArray[i].Passed = true;
    }
}

console.log(output);

function countOccurrences(input, char){
    let count = 0;
    for (let i = 0; i < input.length; i++){
        if (input.charAt(i) === char){
            count++;
        }
    }
    return count;
}

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

Unable to inject a service into an Angular unit test

I am currently working on unit testing an Angular service with the following tools: angular 1.3.8 angular-mocks 1.3.8 karma 0.13.19 jasmine 2.4.1 node 0.10.33 OS: Windows 7 Browser: PhantomJS 2.1.3 However, I am encountering an issue where the Angular s ...

Are Bootstrap Input groups inconsistent?

Hey there! I've been working on the sign-in example, but I seem to have hit a roadblock. In my local setup, the top image is what I see in my browser after running the code, while the desired layout that I found on the Bootstrap site is the one below ...

Discovering duplicated arrays within a sequence

I am facing an issue with my Python code. I have a list containing approximately 131,000 arrays, each with a length of 300. My goal is to identify which arrays are repeating within this list by comparing each array with the others. Here is what I have trie ...

Route Separation with ExpressJS and Socket.IO

As I delve into the world of ExpressJS and Socket.IO, I find myself facing a puzzling situation. My routes are neatly organized in a separate file that I include from my app.js: var express = require('express') , db = require('./db&ap ...

Even in the absence of the element on the page, the VueJS instance is still being invoked

I am encountering an issue where all my VueJS instances are being executed, even if the element associated with them is not present on the page. Currently, I have defined a mixin as follows: var mixin = { methods: { listEvents(parameters) { ...

What is the best way to retrieve the 'items' data stored in this list?

I am working with a list of data that includes 6 categories - bags, shoes, girls, boys. Each category contains the same type of data like id, items (with properties: desc, id, imageUrl, name, price), routeName, and title. My goal is to loop through all ca ...

"Activate the parent window by navigating using the accesskey assigned to the href

I have integrated a bank calculator tool into a website. The calculator opens in a new window, but I am encountering an issue. Users need a shortcut to open the calculator multiple times. I have discovered the accesskey feature, which works the first tim ...

Navigating through a predetermined list of HTML pages with next and previous options

Hey there, I'm in a bit of a quandary at the moment. I've been searching on Google for quite some time now, but unfortunately, I can't seem to find what I'm looking for. Hopefully, you guys can lend me a hand. What I'm trying to d ...

Tips on modifying a Vue app's property externallyHere are some techniques on how

I am curious about changing the property of a vue app from an external source. I want to create a new vue app named 'app' and set 'app.propertyName' to 'someValue'. However, my attempt below did not yield the desired outcome. ...

Countdown Timer App using Flask

I'm currently working on a Flask-based game that involves countdown timers for each round. My goal is to have the timer decrease by 1 second every round without the need to reload the page. I've tried using time.sleep in my Python code to update ...

What is the correct format for an array so that the fputcsv result will display horizontally instead of vertically?

When I inspect the $array in my browser's source code, it looks like this: Array( [0] => 2015-01-15 [1] => 2015-02-15 [2] => 2015-03-15 ) To export this array to a CSV file, I used the following code; $fp = fopen("file.csv", "w"); fp ...

Troubleshooting problem with modifying Bootstrap button styling and hover effects

When creating a navigation menu with Bootstrap, I decided to change the buttons from the primary class to inverse. I then went on to further customize the inverse class using inline CSS to match my specific look and feel requirements. .btn-inverse { b ...

What could be the reason behind the repeated console messages when utilizing jquery to replace the src attribute of images?

Overview: An HTML page with two images, identified as #me1 and #me2 The images initially display 1.jpg and 2.jpg Clicking #me1 triggers a GET request to "randim.php" using jQuery to fetch a random filename, which is then set as the src= attribute ...

Encountering a pair of errors while working with Node.js and Express

(Apologies for the vague title) I have been developing a project using Firebase and Express, but I am encountering some issues. src/index.js import { initializeApp } from "firebase/app"; import { doc, getFirestore } from "firebase/firesto ...

I have a quick question: What is the most effective method for creating PDF templates with Angular and .NET 6, specifically for designs that feature heavy

Seeking the optimal solution for creating PDF templates using Angular and .NET 6? Specifically looking to design templates that heavily feature tables. In my exploration of efficient PDF template creation with Angular and .NET 6, I ventured into using pdf ...

Utilizing ng-href in Angular.js Template: A Guide

I am attempting to develop a simple Single Page Application (SPA) with just one index.html file that includes templates. However, I encountered an issue with the ng-href directive: <a ng-href="#/myPage">myPage</a> This works fine in index.h ...

Guide on enabling automatic rotation using Javascript

Recently, I came across a slider online that unfortunately did not have an autorotate feature. Despite my attempts to add an autorotate function using setTimeout and click functions, I was unsuccessful. This particular slider contains 4 buttons for each s ...

The ScrollToTop feature in MUI component seems to be malfunctioning when paired with the useScrollTrigger hook

I am in the process of developing a custom ScrollToTop component using MUI's useScrollTrigger hook. More information can be found at this link Feel free to check out the sample code here: https://codesandbox.io/s/stackoverlow-mui-usescrolltrigger-er9 ...

Discovering the highest value within an array of objects

I have a collection of peaks in the following format: peaks = 0: {intervalId: 7, time: 1520290800000, value: 54.95125000000001} 1: {intervalId: 7, time: 1520377200000, value: 49.01083333333333} and so on. I am looking to determine the peak with the hig ...

Move the option from one box to another in jQuery and retain its value

Hey guys, I need some assistance with a jQuery function. The first set of boxes works perfectly with the left and right buttons, but the second set is not functioning properly and doesn't display its price value. I want to fix it so that when I click ...