Skip to content Skip to sidebar Skip to footer

Why Indexof In Javascript Not Working?

I'm not sure what I'm doing wrong here. The first instance that I use indexOf it works perfectly fine, but when I use it the second time it's not returning the result that I'm expe

Solution 1:

your code isn't working because when you say:

res.indexOf("f") != -1

this means: "I found an f", but you're treating it as if it means "I did not find an f".

In your case that you want to return false if you find an 'f', but you're returning true. Flip your true and false cases:

if (res.indexOf("f") != -1) {
   returnfalse;
 } else {
   returntrue;
 }

ALSO your for loop is wrong because x starts at 0, so you need to go to < length not <= length of your string.

for (var x=0; x < arr[1].split("").length; x++) {

and now your code works as you wanted it to.

Solution 2:

If you simplify the logic a bit, that's easier to check:

functionmutation(arr) {
  return arr[1].split('').reduce(function(res, x) {
    return arr[0].indexOf(x) >= 0;
  }, true);
}

Thanks Leon for the correction.

Solution 3:

I tried to not chance your logic, the mistake are:

  • You're trying to compare with all characters on the array[0], not only the first.
  • If you find a character equals on the first character on array[0] you should return true.

Correct code:

function mutation(arr) {
  res = "";
  for (var x=0; x<=arr[1].split("").length; x++) {
    if (arr[0].split("")[0].indexOf(arr[1].split("")[x]) !== -1) {
      returntrue;
    }
  }
  returnfalse;
}

Post a Comment for "Why Indexof In Javascript Not Working?"