JavaScript Challenge - Unique Characters in a String

This community-built FAQ covers the “Unique Characters in a String” code challenge in JavaScript. You can find that challenge here, or pick any challenge you like from our list.

Top Discussions on the JavaScript challenge Unique Characters in a String

There are currently no frequently asked questions or top answers associated with this challenge – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this challenge. Ask a question or post a solution by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this challenge, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

Looking for motivation to keep learning? Join our wider discussions in #community

Learn more about how to use this guide.

Found a bug? Report it online, or post in #community:Codecademy-Bug-Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

First challenge! Any feedback would be really appreciated

function uniqueCharacters(stringIn) {

    let results = true;

    if (stringIn == "") {
        return "Error : the string is empty";
    }

    let isUnique;

    for (let i = 0; i < stringIn.length; i++) {

        isUnique = stringIn[i];

        let j = 0;

        while (j < stringIn.length && results) {

            if (j != i && stringIn[j] == stringIn[i] && results) {
                results = false;
            } else {
                results = true;
            }

            j++;
        }

    }

    return results;

}

// Leave this so we can test your code:
module.exports = uniqueCharacters;

Man programming is hard! My brain hurts :smiley: Give me some tips on what I could do better, very new on this.

function uniqueCharacters(stringIn) {
  let countLetters = 0;
  if(stringIn === '') return 'error'
  for(letter of stringIn) { 
    countLetters += stringIn.split(letter).length -1
    if(countLetters > 1) {
      return false
    } else {
      countLetters = 0;
    }
  }
    return true;
}

// Leave this so we can test your code:
module.exports = uniqueCharacters;
function uniqueCharacters(stringIn) {
  if (stringIn.length < 1) 
    return "Invalid argument length." 

  const chars = [...stringIn]
  return chars
    .filter((c, i) => chars.indexOf(c) == i)
    .length === stringIn.length
}

console.log(uniqueCharacters("mother"))
console.log(uniqueCharacters("father"))
console.log(uniqueCharacters(""))
console.log(uniqueCharacters("apple"))
console.log(uniqueCharacters("hello"))

// Leave this so we can test your code:
module.exports = uniqueCharacters;

Hi @christerolsson261144

can you explain your idea here? I’m a bit confused bc you reset the variable after… countLetters = 0

Using the split is actually a nice idea… since you asked I can give one improvement hint:
if the letter is unique, then the string will be split into two chunks (even if the letter is at the beginning/end)
e.g.

"apple".split("a")   // ["", "pple"]
"apple".split("e")   // ["appl", ""]
"apple".split("p")   // ["a", "", "le"]

It means you could shorten the for-block by only using this comparison inside:

if(stringIn.split(letter).length > 2)
  return false

I hope it helps you in your journey… I would not say programming turns easier with time, but with experience, you will have more often success moments during problem-solving… which makes programming really enjoyable

(post deleted by author)

Here is my solution:

function uniqueCharacters(stringIn) {
if(stringIn === ‘’) {
return ‘error’;
}
let stringOut = ;
for(let i = 0; i < stringIn.length; i++) {
if(stringOut.includes(stringIn[i])) {
return false;
} else {
stringOut.push(stringIn[i]);
}
}

return true;

}

uniqueCharacters("");

// Leave this so we can test your code:
module.exports = uniqueCharacters;

I found the easiest way was to use Sets…

    function uniqueCharacters(stringIn) {

      if(stringIn == ""){
      return "Error";
      }

       const array = [];


       for(i = 0; i <= stringIn.length; i++){
       array.push(stringIn[i]);
        }
       const setArray = new Set();

       for(i = 0; i < array.length; i++){
        if(setArray.has(array[i])){
         return false;
  
         }
         else if (setArray.has(array[i]) === false) {
         setArray.add(array[i]);
    
       }

  

     }
   return true; 


 }

 // Leave this so we can test your code:
 module.exports = uniqueCharacters;

function uniqueCharacters(stringIn) {
let answer = true;
if(stringIn == ‘’){
return ‘error: Please provide string’
}
for(let i=0; i<stringIn.length; i++){
for(let j=0; j<stringIn.length; j++){
if(i !== j){
if(stringIn.charAt(i) == stringIn.charAt(j)){
answer = false
}
}
}
}
return answer;
}

console.log(uniqueCharacters(’’))

// Leave this so we can test your code:
module.exports = uniqueCharacters;

Wow, that’s a really unique way of doing it,
I was literally used a double for loop and two returns.

function uniqueCharacters(stringIn) {
  let answer = true;
  if(stringIn == ''){
    return 'error: Please provide string'
  }
  for(let i=0; i<stringIn.length; i++){
    for(let j=0; j<stringIn.length; j++){
      if(i !== j){
        if(stringIn.charAt(i) == stringIn.charAt(j)){
          answer = false
        }
      }
    }
  }
  return answer;
}

console.log(uniqueCharacters(''))

// Leave this so we can test your code:
module.exports = uniqueCharacters;

function uniqueCharacters(stringIn) {
if (!stringIn) {return ‘ERROR: please enter a string’;}
for (i=0;i<stringIn.length;i++){
if (stringIn.lastIndexOf(stringIn[i])!==i){
return false;
}
}
return true;
}

// Leave this so we can test your code:
module.exports = uniqueCharacters;

Well I find sets very useful in this case since they store only unique value

const uniqueCharacters = stringIn => {
  let uniqueStr = [... new Set(stringIn.split(""))].join("");
  return stringIn === "" ? new Error("Empty String!") : stringIn === uniqueStr;
}
 
module.exports = uniqueCharacters;
function uniqueCharacters(stringIn) {
  return stringIn == "" ? new Error ('Empty string') :
     new Set([...stringIn]).size == stringIn.length;
}

// Leave this so we can test your code:
module.exports = uniqueCharacters;

My first challenge. Any advice would be appreciated.

function uniqueCharacters(stringIn) { // Creates a counter to keep track of any repeated integers. let repeated = 0; // Loops through each letter and compares it to the next. for (i = 0; i < stringIn.length; i++) { if (stringIn.split("")[i] === stringIn.split("")[i + 1]) { repeated++; } } if (stringIn === "") { return "Error, empty string"; } else if (repeated > 0) { return false; } else { return true; } }; console.log(uniqueCharacters("apple")) console.log(uniqueCharacters("pear")) console.log(uniqueCharacters("")) // Leave this so we can test your code: module.exports = uniqueCharacters;

you can use markdown notation instead of screenshot, it’s more confortable to read.

You can also use ternary operator instead of if … else if … else … it’s also more confortable to read

return stringIn == "" ? "Error, empty string" : repeated < O

When your return a boolean value you dont need to return true or false, just need to return your condition which is a boolean value

1 Like