subLength(). JavaScript Practice: Arrays, Loops, Objects, Iterators

Hello to everybody!
I got stuck with 2th exercise in JavaScript Practice: Arrays, Loops, Objects, Iterators. I wrote a function, it works pretty well on tests, but CodeCademy doesn’t pass my answer.
What can be wrong with my code? Thank you in advance for reply :slight_smile:

const subLength = (str,char) => {
  let pattern = new RegExp(char,'g');
  let checker = str.match(pattern).length;
  if(checker !== 2){
    return 0;
  }else{
    let arr = str.split('');
    let indexAll = arr
    .map((elem,i) => elem === char ? i : -1)
    .filter(index => index !== -1);
    return indexAll.reduce((a,b) => Math.abs(a-b)+1);
  }
};

SOLVED!
Here is my updated way to solve this task:

const subLength = (str,char) => {
  let pattern = new RegExp(char,'g');
  let reg = str.match(pattern);
  if(reg !== null){
    let checker = reg.length;
    if(checker !== 2){
      return 0;
    }else{
      let arr = str.split('');
      let indexAll = arr
      .map((elem,i) => elem === char ? i : -1)
      .filter(index => index !== -1);
      return indexAll.reduce((a,b) => Math.abs(a-b)+1);
     }
  }else{
    return 0;
  }
};
1 Like

Hello, and welcome to the forums!

The interactive article tests for more than just the examples they provided in the challenge description. One example they didn’t provide and you didn’t account for is if there are no occurrences of the single character in the string.

Try your code with:

subLength('anastasiamazhid', 'e');

Oh, thanks! This is the key :slight_smile:

1 Like

Hi, i am also having trouble getting my code verified by the check answer system on this exercise. What is going wrong? All my tests are working, but i am getting ’ Double check your code. It likely has a syntax error.’ as a response. Here is my code:

const subLength = (string, char) => {
let stringLower = string.toLowerCase();
let splitString = stringLower.split("");
console.log(splitString);

let charCount = 0;
for (i = 0; i < splitString.length; i++)
if (splitString[i] === char) {charCount++}
console.log(charCount);

if (charCount < 2) {return 0}
if (charCount === 2) {
let c1 = splitString.indexOf(char);
let c2 = splitString.lastIndexOf(char);
console.log(c1, c2)
let answer = (c2 - c1);
return answer += 1;
}
if (charCount > 2) {return 0}
}

console.log(subLength(‘summer’, ‘m’));

Hello :slightly_smiling_face:

I tried to use your code and slightly edited it, but mine version doesn’t work too. Here is my code, may be it could help you find best solution:

const subLength = (string, char) => {
	let stringLower = string.toLowerCase();
	let splitString = stringLower.split("");
	let charCount = 0;
	for (i = 0; i < splitString.length; i++){
		if (splitString[i] === char) {
			charCount++;
		}	
	}
	if (charCount === 2) {
		let c1 = splitString.indexOf(char);
		let c2 = splitString.lastIndexOf(char);
		return Math.abs(c2 - c1)+1;
	}else{
		return 0;
	}
}

Hi :slight_smile:.

New to the forums … I have a similar but different issue: my code works but isn’t accepted. I didn’t want to create a new post so will post my code here:

function subLength(str, char) {
    let firstInd = 0;
    let secondInd = 0;
    let thirdInd = 0;

    firstInd = str.indexOf(char);
    secondInd = str.indexOf(char, firstInd + 1);
    thirdInd = str.indexOf(char, secondInd + 1);

    if (firstInd === -1 || secondInd === -1 || thirdInd > -1) {
        return 0;
    } else {
        return secondInd - firstInd + 1;
    }   
};

This works for me and I believe is correct however the strict testing fails it for a reason I’m not seeing. I can see that the successful submissions use a for loop however I thought it would be quicker to slice the string.

I suspect the issue may be the if condition on line 10 (if (firstInd === -1 || secondInd === -1 || thirdInd > -1)) however I can’t see any issues with the logic so hoping for a second pair of eyes.

Any thoughts?

Many thanks.

SOLVED!

I managed to resolve the issue: though my OP shows the thirdInd deceleration ( let thirdInd = 0; ), it was missing from the code I’d tested. Once I added it the code was passed.

Comments / peer review welcome!

The full successful submission was:

function subLength(str, char) {
    let firstInd = 0;
    let secondInd = 0;
    let thirdInd = 0;

    firstInd = str.indexOf(char);
    secondInd = str.indexOf(char, firstInd + 1);
    thirdInd = str.indexOf(char, secondInd + 1);

    if (firstInd === -1 || secondInd === -1 || thirdInd > -1) {
        return 0;
    } else {
        return secondInd - firstInd + 1;
    }   
};

I am having the same issue. All my codes in this section work but I keep getting “Double check your code. It likely has a syntax error.” If it has a syntax error, why am I not getting a red Syntax Error from the compiler?

1 Like

Make sure that all your variables are being declared with let, const, or var (though let and const are preferred).

I’ve found that’s a common problem people run into with the interactive article code checkers, even if the code runs fine otherwise.

1 Like

That was absolutely it! Thank you. In my for loops, I did not declare the index, i with ‘let’. Once I put that in, the Codecademy accepted it:

for (let i = 0; i < numOfItems - 2; i++){
str = str + grocObjArr[i].item + ', ';
}

1 Like

Here is my subLength() solution:

const subLength = (str, char) => {
    const arr = str.split(char);
    const count = stringArray.length - 1;
    return (count === 2) ? arr[1].split('').length + 2 : 0 ;
}

Hope it helps :+1:

So clearly there are way simpler ways of doing it but can anyone explain if my solution is wrong or not? It seems to work when I test it but it keeps telling me to double check it for a syntax error :sweat_smile:

##############################################

const subLength = (word, letter) => {

// Check how many letters
let letterCount = 0;
for (let i = 0; i < word.length; i++) {
if (word[i] === letter) {
letterCount += 1;
}
};
if (letterCount < 2 || letterCount > 2) {
return 0;
};

// Create an array of each letters index
indexArr = ;
for (let i = 0; i < word.length; i++) {
if (word[i] === letter) {
indexArr.push(i);
}
};

// Use the array to find the length between
let between = indexArr[1] - indexArr[0] + 1;
return between;
};

Hey, jrhood.

Not sure what you’re setting indexArr to here? There’s an unknown char showing. Perhaps use the preformatted text (angle brackets in the posting interface) to format the code? You could also indent the code? :slight_smile:

So for example your code would look like:

const subLength = (word, letter) => {

   // Check how many letters
   let letterCount = 0;
   for (let i = 0; i < word.length; i++)  {
      if (word[i] === letter) {
         letterCount += 1;
      }
   };
   if (letterCount < 2 || letterCount > 2) {
      return 0;
   };
   
   // Create an array of each letters index
   indexArr = ;
   for (let i = 0; i < word.length; i++) {
      if (word[i] === letter) {
         indexArr.push(i);
      }
   };
   
   // Use the array to find the length between
   let between = indexArr[1] - indexArr[0] + 1;
   return between;
};

EDIT - so realise what happened: the forum used markdown to format posts and the open close square brackets renders as a square. If you use the code formatting it should resolve this.

1 Like

So it tests fine and confirmed it works as intended. The only issue I can see is that on line 15 where you declare indexArr = [] you need use ‘let’ to declare the variable, so let indexArr[].

When I answered this question I had a similar issue :slight_smile:

The code would therefore be:

const subLength = (word, letter) => {

  // Check how many letters
  let letterCount = 0;
  for (let i = 0; i < word.length; i++)  {
     if (word[i] === letter) {
        letterCount += 1;
     }
  };
  if (letterCount < 2 || letterCount > 2) {
     return 0;
  };
  
  // Create an array of each letters index
  let indexArr = [];
  for (let i = 0; i < word.length; i++) {
     if (word[i] === letter) {
        indexArr.push(i);
     }
  };
  
  // Use the array to find the length between
  let between = indexArr[1] - indexArr[0] + 1;
  return between;
};

console.log(`Word entered is 'example' showing: ${subLength('example', 'x')} no of times`);
console.log(`Word entered is 'example' showing: ${subLength('example', 'e')} no of times`);
console.log(`Word entered is 'disenfranchised' showing: ${subLength('disenfranchised', 'e')} no of times`);

Output is:

Word entered is 'example' showing: 0 no of times
Word entered is 'example' showing: 7 no of times
Word entered is 'disenfranchised' showing: 11 no of times
1 Like

Huh dunno why it came out un-indented when i pasted it in BUT yeah your right i forgot to properly declare it :sweat_smile: That fixed it! Thanks :blush::v:

1 Like

Hello

Also have a small issue with codecademy code checker not verifying my code, although the answers in the console seems to work. Here is my solution to the subLength task:

let subLength = (word, letter) => {
  word = word.toLowerCase();
  letter = letter.toLowerCase();
  let letterArray = [];
  for (let i = 0; i < word.length; i++) {
   if (word[i] === letter) letterArray.push(i);
  };
  if (letterArray.length < 2 || letterArray.length > 2) {
    return console.log(0)
  } else {
    return console.log(letterArray[1] - letterArray[0] + 1)
  };
}

subLength('Saturday', 'a'); // returns 6
subLength('summer', 'm'); // returns 2
subLength('digitize', 'i'); // returns 0
subLength('cheesecake', 'k'); // returns 0

So all examples return fine, but the codeacademy throws this error below:

Tested subLength('funny', 'n') and it did not return 2 .

However my console is returning 2 for this example, so not sure what is wrong, can someone help?

Your function is returning undefined but is printing to the console.

console.log() doesn’t result in a value, so JavaScript evaluates the statement, prints to the console like you requested, then returns undefined. The test is looking for the actual value to be returned, so you need to use return without console.log()

1 Like

Ah indeed! It works now! Thank you :slight_smile:

I got stuck for a while on this one, and this topic came in quite handy trying to solve it, yet I found most of the answers here slightly overcomplicated or with some readability issues. Let me know if this one can be even more simplified since I’m working on that. And I hope you’ll find this useful.

const subLength = (str, x) => {
  let n = str.toLowerCase().split('').filter(letter => letter === x);

  let f = str.indexOf(x);
  let l = str.lastIndexOf(x);

  return (n.length === 2) ? (str.substring(f,l).length +1) : 0;
}

Like the many comments above, my code seems to be working but I don’t seem to be getting approval on it :thinking:

I thought I maybe hadn’t returned correctly but the console.log outside of the function works perfectly. I’ve also tried it with just a plain number without text for the answer but it made no difference?

// Write function below const subLength = (str, char) => { let strSplit = str.split('') let count = 0 for (let i = 0; i <= strSplit.length; i++) { if (strSplit[i] === char) { count++; } } if (count >= 2){ return `'${str}' contains the letter '${char}', ${count} times.`} else { return 0; } } console.log(subLength('cheesecake', 'e'))

Hi all, i’m having trouble with the subLength question, my code as seen below results in ‘undefined’, am I doing something wrong? Thanks all!

// Write function below const subLength = (str, char) => { let charCount = 0; let lengthBetween = 0; for (let i = 0; i < str.legnth; i ++){ if (str[i] == char){ charCount ++; if (charCount !== 2){ return 0; } else { lengthBetween = lengthBetween + i } } return lengthBetween } } console.log(subLength('Saturday', 'a'))