Is there a way to determine if a string has duplicate characters or not?

I am trying to find an effective method for detecting repeated characters within a string, even if they are not placed next to each other. I attempted converting the string into an array and then utilizing nested loops to compare each element of the array against one another, but unfortunately, this approach did not yield the desired results.

function hasRepeatedChars(str) {
    let arr = [];
    for (let i = 0; i < str.length; i++) {
        arr.push(str[i]);
    }

    for (let j = 0; j < arr.length; j++) {
        for (let k = j + 1; k < arr.length; k++) {
            if (arr[j] != arr[k]) {
                return true;
            } else {
                return false;
            }
        }
    }
}

hasRepeatedChars("abadan");

Answer №1

To determine if a string contains any repeated characters, you can create a Set from the string and compare its size to the length of the original string. Since Sets only hold unique values, if there are repeated characters, the size of the Set will be less than the length of the string.

const hasRepeatedCharacters = str => new Set(str).size < str.length;

console.log(hasRepeatedCharacters("hello"));
console.log(hasRepeatedCharacters("laptop"));

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 retrieving a value dynamically with jQuery for each loop

I'm facing a challenge and need some guidance to figure it out. It seems like I might be missing a crucial piece of information here. My current task involves extracting values from a JSON response. The data includes two key elements - a list of names ...

Is there a way to include a text file in HTML for referencing or posting on my website?

Managing a website where my colleagues frequently post updates can be time-consuming as I am the only one knowledgeable in html and css. I find myself constantly formatting their posts and creating new pages for them. I am exploring ways to simplify this ...

Utilizing the same uuid twice along with Vuex and the unique identifier generation tool uuidv4

Within my vuex store, there is a function to create a post. This function generates a json Object containing a unique uuid using uuidv4(). However, I have noticed that if I execute the function multiple times, the uuid remains the same each time (unless I ...

Load the template.html file using pure JavaScript without relying on jQuery

At the moment, I am implementing a template load process in the following way: $('#mydiv').load("template1.html") While I am currently relying on jQuery for this functionality, I am curious to know how I can achieve the same outcome using pure ...

Creating a HTML drop-down menu that requires the user to make a selection in the first drop-down before moving on to the next drop

Is there a way to prevent the user from selecting the second drop-down menu (time) until they have chosen an option from the first drop-down menu (movie)?<html> <body> <h1>Using the select element in HTML</h1> <p>The selec ...

Issue with TypeScript in React Native: Error message stating that objects cannot be used as a React child (specifically found: [object Date])

Every time I attempt to display the contents of hours, I encounter an error that is puzzling to me because it seems to be related to a date object. How can I properly address the following issue : "Objects are not valid as a React child (found: [object D ...

React: Deep requiring has been phased out with the latest version of uuid. Make sure to only require the top-level

My React application is displaying the button successfully, but I am encountering an error. In my index.js file, I used const uuidv4 = require('uuid/v4');, which is now deprecated as of [email protected] Please ensure you require the top-le ...

Error message thrown on the login page: "Attempting to access property 'push' of an undefined object"

I'm currently working on a login page using JWT and I'm facing an issue with trying to redirect the user to the home page after successful login. I am using this.props.history.push("/") for redirection but I keep getting an error: TypeError: Cann ...

What causes the inconsistency in TypeScript's structure typing?

It is well-known that TypeScript applies structure typing, as demonstrated in the following example: interface Vector { x: number; y: number; } interface NamedVector { x: number; y: number; name: string; } function calculateLength(v: Vecto ...

Injecting components into the DOM using JavaScript in Vue.js

I am currently developing a GUI for a webgame using Vue.JS and opting to use http-vue-loader instead of Webpack or similar tools. Personally, I find them cumbersome and prefer to avoid using them. Typically, in order to integrate my components into the DO ...

Error encountered in AngularJS and JSON server: [$injector:unpr] An unidentified provider was found: $resourceProvider <- $resource <- menuFactory

Hello everyone, I recently created a small AngularJS application and utilized a JSON server for my backend operations. Unfortunately, I am encountering an issue with the provider in my code. Upon running it, I am receiving errors as shown below: Uncaugh ...

Problem with detecting collisions algorithm

Here is the jsfiddle I've been working on: http://jsfiddle.net/TLYZS/ Upon debugging the code and inspecting the collision function, it's evident that the collision is functioning properly when the user overlaps with the other character. However ...

The browser is unable to display THREE.js rendering

I recently followed a tutorial on using the THREE.js library to create a solar system. However, I am encountering an issue where the result is not displaying in the browser window. Can someone please assist me in identifying any errors in the code? Below ...

What benefits can be gained from utilizing the module pattern or objects to establish Angular components?

I'm contemplating the value of writing angular code in different ways. One way is like this: (function(angular, module) { 'use strict'; module.controller('MyCtrl', function($scope) { // maybe utilize helperFunction here ...

Unlock the potential of Bootstrap 4 in Vue.js 2 without the need for bootstrap-vue

I'm interested in finding a way to incorporate bootstrap 4 into my vue.js 2.6 framework. Despite the abundance of tutorials available, many of them are outdated as of late 2020, or they insist on using bootstrap-vue, which introduces unwanted addition ...

Enhancing Angular Directives with Dynamic Templates upon Data Loading

I am facing an issue with a directive that is receiving data from an api call. While the directive itself functions properly, the problem seems to be occurring because the directive loads before the api call is complete. As a result, instead of the expecte ...

The variable in React does not get updated by a function

I am currently using axios to retrieve a map in my main app, which will then be distributed to other variables within the program. However, I have encountered an issue. When I try to use 'onClick' on a dropdown select, I want it to trigger that e ...

Issue with V-checkbox input-value not triggering correctly on change

Query Example: <query #[`${instanceItemIdKey}`]="{ item }"> <v-checkbox :input="item.content" @modify="$notify('onPermissionUpdate', item)" ></v-checkbox> </query> The information that influ ...

Utilize Knockout.js to generate a table based on a Json response

I'm currently working on a project that involves creating a table using JSON response and Knockout.js. Here's how I've set it up: First, in my JavaScript file: $(document).ready(function() { $.ajax({ method : "POST", url ...

Encountering an error message stating "Type does not match FunctionComponent<Props>" and "Type is lacking the properties from type 'React Element<any, any>'"

As I work on integrating TypeScript into my code, I keep encountering an error that seems to be related to my Props type. The specific error message I'm facing is: Type '({ volume, onload, isMuted, src, mediaType, ...config }: PropsWithChildren&l ...