Check for characters in a string being uniqueHow to check empty/undefined/null string in JavaScript?How do I check if an element is hidden in jQuery?How do I check if an array includes an object in JavaScript?Setting “checked” for a checkbox with jQuery?How to check if a string “StartsWith” another string?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?Check if a variable is a string in JavaScriptHow to check if an object is an array?Is it possible to apply CSS to half of a character?

Today is the Center

What is a clear way to write a bar that has an extra beat?

What are these boxed doors outside store fronts in New York?

Is it unprofessional to ask if a job posting on GlassDoor is real?

Do other languages have an "irreversible aspect"?

Important Resources for Dark Age Civilizations?

Why is consensus so controversial in Britain?

What is the word for reserving something for yourself before others do?

What's that red-plus icon near a text?

Do I have a twin with permutated remainders?

What defenses are there against being summoned by the Gate spell?

Why doesn't H₄O²⁺ exist?

Why does Kotter return in Welcome Back Kotter?

Why is 150k or 200k jobs considered good when there's 300k+ births a month?

How much of data wrangling is a data scientist's job?

Could an aircraft fly or hover using only jets of compressed air?

Can you really stack all of this on an Opportunity Attack?

What's the point of deactivating Num Lock on login screens?

Is it possible to do 50 km distance without any previous training?

What would happen to a modern skyscraper if it rains micro blackholes?

Paid for article while in US on F-1 visa?

How can I prevent hyper evolved versions of regular creatures from wiping out their cousins?

Theorems that impeded progress

Can a monk's single staff be considered dual wielded, as per the Dual Wielder feat?



Check for characters in a string being unique


How to check empty/undefined/null string in JavaScript?How do I check if an element is hidden in jQuery?How do I check if an array includes an object in JavaScript?Setting “checked” for a checkbox with jQuery?How to check if a string “StartsWith” another string?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?Check if a variable is a string in JavaScriptHow to check if an object is an array?Is it possible to apply CSS to half of a character?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








7















I implemented my algorithm for checking if the string passed in is unique. I feel like my algorithm is correct, but obviously in certain cases it gives the wrong results. Why?






function isUnique(str) 
let sortedArr = str.split('').sort();
for (let [i, char] of sortedArr.entries())
if (char === sortedArr[i + 1])
return false
else
return true




console.log(isUnique('heloworld')) // true












share|improve this question
























  • FWIW: function noDuplicatedChars() const chars = new Set(); for (let c of str) if (chars.has(c)) return false; chars.add(c); return true; is a faster alternative.

    – Frax
    2 days ago

















7















I implemented my algorithm for checking if the string passed in is unique. I feel like my algorithm is correct, but obviously in certain cases it gives the wrong results. Why?






function isUnique(str) 
let sortedArr = str.split('').sort();
for (let [i, char] of sortedArr.entries())
if (char === sortedArr[i + 1])
return false
else
return true




console.log(isUnique('heloworld')) // true












share|improve this question
























  • FWIW: function noDuplicatedChars() const chars = new Set(); for (let c of str) if (chars.has(c)) return false; chars.add(c); return true; is a faster alternative.

    – Frax
    2 days ago













7












7








7


1






I implemented my algorithm for checking if the string passed in is unique. I feel like my algorithm is correct, but obviously in certain cases it gives the wrong results. Why?






function isUnique(str) 
let sortedArr = str.split('').sort();
for (let [i, char] of sortedArr.entries())
if (char === sortedArr[i + 1])
return false
else
return true




console.log(isUnique('heloworld')) // true












share|improve this question
















I implemented my algorithm for checking if the string passed in is unique. I feel like my algorithm is correct, but obviously in certain cases it gives the wrong results. Why?






function isUnique(str) 
let sortedArr = str.split('').sort();
for (let [i, char] of sortedArr.entries())
if (char === sortedArr[i + 1])
return false
else
return true




console.log(isUnique('heloworld')) // true








function isUnique(str) 
let sortedArr = str.split('').sort();
for (let [i, char] of sortedArr.entries())
if (char === sortedArr[i + 1])
return false
else
return true




console.log(isUnique('heloworld')) // true





function isUnique(str) 
let sortedArr = str.split('').sort();
for (let [i, char] of sortedArr.entries())
if (char === sortedArr[i + 1])
return false
else
return true




console.log(isUnique('heloworld')) // true






javascript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 2 days ago









Peter Mortensen

13.9k1987113




13.9k1987113










asked 2 days ago









user3763875user3763875

695




695












  • FWIW: function noDuplicatedChars() const chars = new Set(); for (let c of str) if (chars.has(c)) return false; chars.add(c); return true; is a faster alternative.

    – Frax
    2 days ago

















  • FWIW: function noDuplicatedChars() const chars = new Set(); for (let c of str) if (chars.has(c)) return false; chars.add(c); return true; is a faster alternative.

    – Frax
    2 days ago
















FWIW: function noDuplicatedChars() const chars = new Set(); for (let c of str) if (chars.has(c)) return false; chars.add(c); return true; is a faster alternative.

– Frax
2 days ago





FWIW: function noDuplicatedChars() const chars = new Set(); for (let c of str) if (chars.has(c)) return false; chars.add(c); return true; is a faster alternative.

– Frax
2 days ago












2 Answers
2






active

oldest

votes


















24














return immediately terminates the function, so only the first iteration if your for loop will ever run. Instead, you should check for whether all characters are unique (if not, return false inside the loop), else return true after the end of the loop:






function isUnique(str) 
let sortedArr = str.split('').sort();
for(let [i,char] of sortedArr.entries())
if(char === sortedArr[i + 1])
return false


return true


console.log(isUnique('heloworld'))





But it would probably be a lot easier to use a Set, and see if its size is equal to the length of the string:






function isUnique(str) 
return new Set(str).size === str.length;


console.log(isUnique('heloworld'))
console.log(isUnique('abc'))





See comment, thanks Patrick: if you need to account for characters composed of multiple UCS-2 code points (𝟙𝟚𝟛😎😜🙃 etc), call the string iterator and check how many items it returns, which can be done with spread or Array.from (because otherwise, str.length won't evaluate to the right number of individual characters):






function isUnique(str) 
return new Set(str).size === [...str].length;


console.log(isUnique('😜'));
console.log(isUnique('😜😜'));








share|improve this answer




















  • 1





    Not sure if this matters but for multi-unit code points you get the wrong answer, e.g. isUnique('😀😁') === false

    – Patrick Roberts
    2 days ago







  • 5





    The fix is relatively simple though: return new Set(str).size === Array.from(str).length;

    – Patrick Roberts
    2 days ago


















0














Only first iteration in your for loop is run (because you always execute 'return'). Instead you can use following code






function isUnique(str, t=) 

return ![...str].some(c=> t[c]=c in t)


console.log('heloworld =>',isUnique('heloworld'));
console.log('helo =>',isUnique('helo'));








share|improve this answer

























  • Why is r a parameter?

    – JollyJoker
    2 days ago











  • r (I rename it to t) is temporary hash map (define in tricky way as default param)

    – Kamil Kiełczewski
    2 days ago












Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55487722%2fcheck-for-characters-in-a-string-being-unique%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









24














return immediately terminates the function, so only the first iteration if your for loop will ever run. Instead, you should check for whether all characters are unique (if not, return false inside the loop), else return true after the end of the loop:






function isUnique(str) 
let sortedArr = str.split('').sort();
for(let [i,char] of sortedArr.entries())
if(char === sortedArr[i + 1])
return false


return true


console.log(isUnique('heloworld'))





But it would probably be a lot easier to use a Set, and see if its size is equal to the length of the string:






function isUnique(str) 
return new Set(str).size === str.length;


console.log(isUnique('heloworld'))
console.log(isUnique('abc'))





See comment, thanks Patrick: if you need to account for characters composed of multiple UCS-2 code points (𝟙𝟚𝟛😎😜🙃 etc), call the string iterator and check how many items it returns, which can be done with spread or Array.from (because otherwise, str.length won't evaluate to the right number of individual characters):






function isUnique(str) 
return new Set(str).size === [...str].length;


console.log(isUnique('😜'));
console.log(isUnique('😜😜'));








share|improve this answer




















  • 1





    Not sure if this matters but for multi-unit code points you get the wrong answer, e.g. isUnique('😀😁') === false

    – Patrick Roberts
    2 days ago







  • 5





    The fix is relatively simple though: return new Set(str).size === Array.from(str).length;

    – Patrick Roberts
    2 days ago















24














return immediately terminates the function, so only the first iteration if your for loop will ever run. Instead, you should check for whether all characters are unique (if not, return false inside the loop), else return true after the end of the loop:






function isUnique(str) 
let sortedArr = str.split('').sort();
for(let [i,char] of sortedArr.entries())
if(char === sortedArr[i + 1])
return false


return true


console.log(isUnique('heloworld'))





But it would probably be a lot easier to use a Set, and see if its size is equal to the length of the string:






function isUnique(str) 
return new Set(str).size === str.length;


console.log(isUnique('heloworld'))
console.log(isUnique('abc'))





See comment, thanks Patrick: if you need to account for characters composed of multiple UCS-2 code points (𝟙𝟚𝟛😎😜🙃 etc), call the string iterator and check how many items it returns, which can be done with spread or Array.from (because otherwise, str.length won't evaluate to the right number of individual characters):






function isUnique(str) 
return new Set(str).size === [...str].length;


console.log(isUnique('😜'));
console.log(isUnique('😜😜'));








share|improve this answer




















  • 1





    Not sure if this matters but for multi-unit code points you get the wrong answer, e.g. isUnique('😀😁') === false

    – Patrick Roberts
    2 days ago







  • 5





    The fix is relatively simple though: return new Set(str).size === Array.from(str).length;

    – Patrick Roberts
    2 days ago













24












24








24







return immediately terminates the function, so only the first iteration if your for loop will ever run. Instead, you should check for whether all characters are unique (if not, return false inside the loop), else return true after the end of the loop:






function isUnique(str) 
let sortedArr = str.split('').sort();
for(let [i,char] of sortedArr.entries())
if(char === sortedArr[i + 1])
return false


return true


console.log(isUnique('heloworld'))





But it would probably be a lot easier to use a Set, and see if its size is equal to the length of the string:






function isUnique(str) 
return new Set(str).size === str.length;


console.log(isUnique('heloworld'))
console.log(isUnique('abc'))





See comment, thanks Patrick: if you need to account for characters composed of multiple UCS-2 code points (𝟙𝟚𝟛😎😜🙃 etc), call the string iterator and check how many items it returns, which can be done with spread or Array.from (because otherwise, str.length won't evaluate to the right number of individual characters):






function isUnique(str) 
return new Set(str).size === [...str].length;


console.log(isUnique('😜'));
console.log(isUnique('😜😜'));








share|improve this answer















return immediately terminates the function, so only the first iteration if your for loop will ever run. Instead, you should check for whether all characters are unique (if not, return false inside the loop), else return true after the end of the loop:






function isUnique(str) 
let sortedArr = str.split('').sort();
for(let [i,char] of sortedArr.entries())
if(char === sortedArr[i + 1])
return false


return true


console.log(isUnique('heloworld'))





But it would probably be a lot easier to use a Set, and see if its size is equal to the length of the string:






function isUnique(str) 
return new Set(str).size === str.length;


console.log(isUnique('heloworld'))
console.log(isUnique('abc'))





See comment, thanks Patrick: if you need to account for characters composed of multiple UCS-2 code points (𝟙𝟚𝟛😎😜🙃 etc), call the string iterator and check how many items it returns, which can be done with spread or Array.from (because otherwise, str.length won't evaluate to the right number of individual characters):






function isUnique(str) 
return new Set(str).size === [...str].length;


console.log(isUnique('😜'));
console.log(isUnique('😜😜'));








function isUnique(str) 
let sortedArr = str.split('').sort();
for(let [i,char] of sortedArr.entries())
if(char === sortedArr[i + 1])
return false


return true


console.log(isUnique('heloworld'))





function isUnique(str) 
let sortedArr = str.split('').sort();
for(let [i,char] of sortedArr.entries())
if(char === sortedArr[i + 1])
return false


return true


console.log(isUnique('heloworld'))





function isUnique(str) 
return new Set(str).size === str.length;


console.log(isUnique('heloworld'))
console.log(isUnique('abc'))





function isUnique(str) 
return new Set(str).size === str.length;


console.log(isUnique('heloworld'))
console.log(isUnique('abc'))





function isUnique(str) 
return new Set(str).size === [...str].length;


console.log(isUnique('😜'));
console.log(isUnique('😜😜'));





function isUnique(str) 
return new Set(str).size === [...str].length;


console.log(isUnique('😜'));
console.log(isUnique('😜😜'));






share|improve this answer














share|improve this answer



share|improve this answer








edited 2 days ago









Patrick Roberts

21.2k33677




21.2k33677










answered 2 days ago









CertainPerformanceCertainPerformance

97.8k165887




97.8k165887







  • 1





    Not sure if this matters but for multi-unit code points you get the wrong answer, e.g. isUnique('😀😁') === false

    – Patrick Roberts
    2 days ago







  • 5





    The fix is relatively simple though: return new Set(str).size === Array.from(str).length;

    – Patrick Roberts
    2 days ago












  • 1





    Not sure if this matters but for multi-unit code points you get the wrong answer, e.g. isUnique('😀😁') === false

    – Patrick Roberts
    2 days ago







  • 5





    The fix is relatively simple though: return new Set(str).size === Array.from(str).length;

    – Patrick Roberts
    2 days ago







1




1





Not sure if this matters but for multi-unit code points you get the wrong answer, e.g. isUnique('😀😁') === false

– Patrick Roberts
2 days ago






Not sure if this matters but for multi-unit code points you get the wrong answer, e.g. isUnique('😀😁') === false

– Patrick Roberts
2 days ago





5




5





The fix is relatively simple though: return new Set(str).size === Array.from(str).length;

– Patrick Roberts
2 days ago





The fix is relatively simple though: return new Set(str).size === Array.from(str).length;

– Patrick Roberts
2 days ago













0














Only first iteration in your for loop is run (because you always execute 'return'). Instead you can use following code






function isUnique(str, t=) 

return ![...str].some(c=> t[c]=c in t)


console.log('heloworld =>',isUnique('heloworld'));
console.log('helo =>',isUnique('helo'));








share|improve this answer

























  • Why is r a parameter?

    – JollyJoker
    2 days ago











  • r (I rename it to t) is temporary hash map (define in tricky way as default param)

    – Kamil Kiełczewski
    2 days ago
















0














Only first iteration in your for loop is run (because you always execute 'return'). Instead you can use following code






function isUnique(str, t=) 

return ![...str].some(c=> t[c]=c in t)


console.log('heloworld =>',isUnique('heloworld'));
console.log('helo =>',isUnique('helo'));








share|improve this answer

























  • Why is r a parameter?

    – JollyJoker
    2 days ago











  • r (I rename it to t) is temporary hash map (define in tricky way as default param)

    – Kamil Kiełczewski
    2 days ago














0












0








0







Only first iteration in your for loop is run (because you always execute 'return'). Instead you can use following code






function isUnique(str, t=) 

return ![...str].some(c=> t[c]=c in t)


console.log('heloworld =>',isUnique('heloworld'));
console.log('helo =>',isUnique('helo'));








share|improve this answer















Only first iteration in your for loop is run (because you always execute 'return'). Instead you can use following code






function isUnique(str, t=) 

return ![...str].some(c=> t[c]=c in t)


console.log('heloworld =>',isUnique('heloworld'));
console.log('helo =>',isUnique('helo'));








function isUnique(str, t=) 

return ![...str].some(c=> t[c]=c in t)


console.log('heloworld =>',isUnique('heloworld'));
console.log('helo =>',isUnique('helo'));





function isUnique(str, t=) 

return ![...str].some(c=> t[c]=c in t)


console.log('heloworld =>',isUnique('heloworld'));
console.log('helo =>',isUnique('helo'));






share|improve this answer














share|improve this answer



share|improve this answer








edited 2 days ago

























answered 2 days ago









Kamil KiełczewskiKamil Kiełczewski

14k87397




14k87397












  • Why is r a parameter?

    – JollyJoker
    2 days ago











  • r (I rename it to t) is temporary hash map (define in tricky way as default param)

    – Kamil Kiełczewski
    2 days ago


















  • Why is r a parameter?

    – JollyJoker
    2 days ago











  • r (I rename it to t) is temporary hash map (define in tricky way as default param)

    – Kamil Kiełczewski
    2 days ago

















Why is r a parameter?

– JollyJoker
2 days ago





Why is r a parameter?

– JollyJoker
2 days ago













r (I rename it to t) is temporary hash map (define in tricky way as default param)

– Kamil Kiełczewski
2 days ago






r (I rename it to t) is temporary hash map (define in tricky way as default param)

– Kamil Kiełczewski
2 days ago


















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55487722%2fcheck-for-characters-in-a-string-being-unique%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

getting Checkpoint VPN SSL Network Extender working in the command lineHow to connect to CheckPoint VPN on Ubuntu 18.04LTS?Will the Linux ( red-hat ) Open VPNC Client connect to checkpoint or nortel VPN gateways?VPN client for linux machine + support checkpoint gatewayVPN SSL Network Extender in FirefoxLinux Checkpoint SNX tool configuration issuesCheck Point - Connect under Linux - snx + OTPSNX VPN Ububuntu 18.XXUsing Checkpoint VPN SSL Network Extender CLI with certificateVPN with network manager (nm-applet) is not workingWill the Linux ( red-hat ) Open VPNC Client connect to checkpoint or nortel VPN gateways?VPN client for linux machine + support checkpoint gatewayImport VPN config files to NetworkManager from command lineTrouble connecting to VPN using network-manager, while command line worksStart a VPN connection with PPTP protocol on command linestarting a docker service daemon breaks the vpn networkCan't connect to vpn with Network-managerVPN SSL Network Extender in FirefoxUsing Checkpoint VPN SSL Network Extender CLI with certificate

Cannot Extend partition with GParted The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) 2019 Community Moderator Election ResultsCan't increase partition size with GParted?GParted doesn't recognize the unallocated space after my current partitionWhat is the best way to add unallocated space located before to Ubuntu 12.04 partition with GParted live?I can't figure out how to extend my Arch home partition into free spaceGparted Linux Mint 18.1 issueTrying to extend but swap partition is showing as Unknown in Gparted, shows proper from fdiskRearrange partitions in gparted to extend a partitionUnable to extend partition even though unallocated space is next to it using GPartedAllocate free space to root partitiongparted: how to merge unallocated space with a partition

NetworkManager fails with “Could not find source connection”Trouble connecting to VPN using network-manager, while command line worksHow can I be notified about state changes to a VPN adapterBacktrack 5 R3 - Refuses to connect to VPNFeed all traffic through OpenVPN for a specific network namespace onlyRun daemon on startup in Debian once openvpn connection establishedpfsense tcp connection between openvpn and lan is brokenInternet connection problem with web browsers onlyWhy does NetworkManager explicitly support tun/tap devices?Browser issues with VPNTwo IP addresses assigned to the same network card - OpenVPN issues?Cannot connect to WiFi with nmcli, although secrets are provided