Jiang Yuxin
Jiang Yuxin

Reputation: 381

Create a function that takes a string and returns either true or false depending on whether or not the string has repeated characters

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.

Upvotes: 3

Views: 491

Answers (1)

kind user
kind user

Reputation: 41893

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"));

Upvotes: 3

Related Questions