2

In the following code, why does every character appear to be equal to every other character?

Write a JavaScript function that takes a sentence as an argument and determines which word in that sentence has the greatest number of repeated letters (the repeated letters do not have to be consecutive).

If the sentence has multiple words with the same max of repeated letters, return them all in an Array.

var repeatedLettersInAString = function(){
    var repeatedLetterCount = 0;
    var wordsWithRepeatedLetters = {};
    var userString = prompt("enter your string", "it will go here!").split(' ');

    /* var i selects the array element, var x will be the
    character to which var n will be compared. */

    console.log(userString);

    for(var i = 0; i < userString.length; i++){
        console.log(userString[i] + " userString");
        for (var x = 0; x < userString[i].length; x++){
            for (var n = 0; n < userString[i].length; n++){

                if (userString[i].charAt(x) === userString[i].charAt(n), x!==n){
                    repeatedLetterCount++;
                    wordsWithRepeatedLetters[i] = userString[i];
                    console.log(wordsWithRepeatedLetters);
                }else{
                    console.log("There are no repeating characters");
                }
            }
        }
    }

    console.log(repeatedLetterCount);
    console.log(wordsWithRepeatedLetters);
};
repeatedLettersInAString();
Sam Hanley
  • 4,498
  • 7
  • 32
  • 56
  • 1
    The comma in your `if` statement should be logical and `&&` – Johnny Mopp Dec 28 '15 at 19:28
  • @jcubic, what does that matter? This isn't a "homework dump" type of request, the OP has produced mostly-working code and is asking a clear, specific question about something they're stuck on. – Sam Hanley Dec 28 '15 at 19:36

1 Answers1

5

Let's look at one specific line from your code that caught my eye:

if (userString[i].charAt(x) === userString[i].charAt(n), x!==n){

Notice something unusual here: the comma in the middle of the expression. According to the MDN, here's how the comma operator works:

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.

The important bit here is "returns the value of the last operand". That is to say, your if statement is always going to be true unless x and n are equal, which doesn't appear to be your desired behavior. I'm thinking that what you're actually aiming for is the case where both expressions are true. If that's the case, you need to use the && operator (the JavaScript logical "and" operator) in place of the comma.

Sam Hanley
  • 4,498
  • 7
  • 32
  • 56