3

var arr = [];
repeatcount = 0;

function isogram(str) {
  for (var i = 0; i < str.length; i++) {
    for (var g = 0; g < arr.length; g++) {
      if (str[i] != arr[g]) {
        arr.push(str[i]);
      }
    }
  }
  if (arr.length != str.length) {
    return false
  } else {
    return true
  }
}


document.write(isogram("jiang"));

console.log(arr);

When I am using console.log(arr), I found that the arr is empty, and I don't know why. The approach I am using is basically creating an array that stores non-repeating character then compare the length, if the length is different then there is repeating character.

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Jiang Yuxin
  • 381
  • 1
  • 9
  • 2
    `arr.length` is initially `0`. So your inner loop will never run – Nick Parsons Dec 05 '19 at 00:59
  • That's the problem I thought of, is there any way for me to fix it? – Jiang Yuxin Dec 05 '19 at 01:00
  • @JiangYuxin use `str.length` instead of `arr.length`. There are however efficient solutions to the actual problem you are looking at https://stackoverflow.com/questions/33656708/check-for-repeated-characters-in-a-string-javascript/33657083 – Prasanna Dec 05 '19 at 01:03

1 Answers1

3

Since arr length at the beginning equals to 0, the inner loop is never fired.

g < arr.length // is always false

What I would suggest you is to get rid of the inner loop and use a simple condition instead - if current letter is not inside arr yet - push it, if there is - don't.

var arr = [];
repeatcount = 0;

function isogram(str) {
  for (var i = 0; i < str.length; i++) {
    if (arr.indexOf(str[i]) === -1) {
       arr.push(str[i]);
    } else {
      return false;
    }
  }
  
  return arr.length === str.length;
}

console.log(isogram("jiang"));
console.log(isogram("jiiang"));

Bonus: One line solution:

const isogram = (str) => [...str].length === [...new Set(str)].length;

console.log(isogram("jiang"));
console.log(isogram("jiiang"));
kind user
  • 40,029
  • 7
  • 67
  • 77
  • arr.indexOf(str[i]) === -1 . what does the -1 mean? Sorry if the question is stupid, I just started learning js – Jiang Yuxin Dec 05 '19 at 01:05
  • 1
    The function could also return *false* as soon as the *if* condition is false, or *true* otherwise. ;-) – RobG Dec 05 '19 at 01:06
  • 1
    @JiangYuxin If there is no specified element inside array yet, it's index is equal to `-1` – kind user Dec 05 '19 at 01:07