Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using indexOf() to compare characters in an Array

Tags:

javascript

  function mutation(arr) {

  var tester = arr[1].split('');

  for (var i = 0; i < tester.length; i ++) {
    if (!arr[0].indexOf(tester[i])) return false;
  }
  return true;
  }

  mutation(["hello", "hey"]);

Here I should return true if the string in the first element of the array contains all of the letters of the string in the second element of the array.

I do not see any problems with this code but it passes like only 90% of the tests and I do not know why. And I can not see a pattern there — what exact conditions should I meet to fail the test.

like image 361
Alex Bykov Avatar asked Nov 18 '15 09:11

Alex Bykov


People also ask

Can you use indexOf on an array?

IndexOf(Array, Object, Int32) Searches for the specified object in a range of elements of a one-dimensional array, and returns the index of its first occurrence. The range extends from a specified index to the end of the array.

What is the function of the indexOf () in arrays?

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

How do you find the indexOf of an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.

What does indexOf find?

Definition and Usage. The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found.


1 Answers

The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.

String.prototype.indexOf() returns -1 if value was't found, that is why your statement doesn't work.

Change to:

if (arr[0].indexOf(tester[i]) < 0) return false;
like image 94
Alexandr Lazarev Avatar answered Oct 02 '22 18:10

Alexandr Lazarev