0

If I enter "12314" in the 'word' string below, everything works as intended. If I enter characters such as "abacd", the code fails. Can anyone tell me why? (1 in [1,2,3,1,4]) works, but ('a' in [a,b,a,c,d] fails. I'm fairly new to Javascript.

var word = "abacd";

function duplicateEncode(word){

  var repeat = [];
  var result = [];
  var letters = word.split('');

  for (i=0; i < letters.length; i++){
    if (letters[i] in repeat) {
        result.push(")");
    } else {
        result.push("(");
    }
    repeat.push(letters[i]);
  }
  return result;
}
3
  • "it fails"... what error do you get? Commented Sep 14, 2016 at 12:28
  • Can you please specify the desired output Commented Sep 14, 2016 at 12:29
  • I'm looking for "(" the first time a character is encountered in the string and ")" if it's already been found. "abacd" should return "(()((" and "12314" should return "((()(". Commented Sep 14, 2016 at 12:32

2 Answers 2

1

in operator:

A string or symbol representing a property name or array index (non-symbols will be coerced to strings).

In your case it's working because its looking at the index not the value of the string. When using the 'in' operator on an array its using the index as the properties


Play around with this:

> 1 in [1,2] //-> true
> 1 in [1]   //-> false (only one item in the list
> 1 in [2,2] // -> true


> Object.keys([2,3,4])  // -> ['0', '1', '2' ]
//in your case you would want to use indexOf
>['a','b','c'],indexOf('a') -> 0
>['a','b','c'],indexOf('e') -> -1

To fix your issue replace in with:

for (i=0; i < letters.length; i++){
 if (repeat.indexOf(letter[i]) > -1) {
    result.push(")");
 } else {
    result.push("(");
 }
 repeat.push(letters[i]);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you Nix, that helps. Can you tell me how I would search the letter array for a specific character?
You would want to use index of. ['a','b','c'],indexOf('a') would return the index if it finds it, if not it will return -1
@Nix you can move code of pushing in repeat in else block. This will ensure only unique values in repeat. Sample Fiddle
0

try following code...

function duplicateEncode(word){

  var repeat = [];
  var result = [];
  var letters = word.split('');
  for (i=0; i < letters.length; i++){
      if (repeat.indexOf(letters[i]) != -1) {
          result.push(")");
      } else {
          result.push("(");
      }
      repeat.push(letters[i]);
   }
   return result;
 }

2 Comments

Thank you, that fixes the problem.
@JamesBeau Pleases mark it as correct option... thank you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.