Using indexOf() to compare characters in an Array - 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.

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;

This won't work because you are classing the first position (0 position) as not acceptable.
Your condition will only be true for values which aren't greater than 0, when 0 should also be valid.
Therefore change it so that it only returns false for values which are less than 0.
Change this line:
if (!arr[0].indexOf(tester[i])) return false;
To:
if (arr[0].indexOf(tester[i]) < 0) return false;

Things were really obvious — Upper/LowerCase() issue. This works now:
function mutation(arr) {
arr[0] = arr[0].toLowerCase();
arr[1] = arr[1].toLowerCase();
var tester = arr[1].split('');
for (var i = 0; i < tester.length; i ++) {
if (arr[0].indexOf(tester[i]) == -1) return false;
}
return true;
}
mutation(["hello", "hey"]);
And of course I have not noticed an obvious 0 position issue:
if (arr[0].indexOf(tester[i]) == -1) return false;
^ this is correct.
Thanks everyone!

Related

Writing indexOf function in JavaScript

I am new to JavaScript. I have created a indexof function in but it is not giving the correct output:
Question is:
/*
Implement a function called indexOf that accepts two parameters: a string and a character, and returns the first index of character in the string.
*/
This is my code:
function indexOf(string, character) {
let result = string;
let i = 0;
let output = 1;
while (i < result.length) {
if (result[i] === character) {
output = output + indexOf[i];
}
}
return output;
}
I want to know what i am doing wrong. Please Help.
You are making things a little harder than you need to. If you want to do this without calling the built-in indexOf(), which I assume is the point of the exercise, you just need to return from the function as soon as your condition matches. The instructions say "return the first index" — that's the i in your loop.
If you make it through the loop without finding something it's traditional to return -1:
function indexOf(string, character) {
let i=0;
while(i < string.length){
if(string[i] == character){ // yes? just return the index i
return i
}
i++ // no? increase i and move on to next loop iteration
}
return -1; // made it through the loop and without returning. This means no match was found.
}
console.log(indexOf("Mark Was Here", "M"))
console.log(indexOf("Mark Was Here", "W"))
console.log(indexOf("Mark Was Here", "X"))
Assuming from your question that the exercise is to only match the first occurrence of a character and not a substring (multiple characters in a row), then the most direct way to do it is the following:
const indexOf = (word, character) => {
for (let i = 0; i < word.length; i++) {
if (word[i] === character) {
return i;
}
}
return -1;
}
If you also need to match substrings, leave a comment on this answer if you can't figure it out and I'll help you along.
indexOf() is a built in method for strings that tells you the index of a particular character in a word. Note that this will always return the index of the FIRST matching character.-
You can write something like:
function indexOf(string, character){
return string.indexOf(character)
}
So if I were to use my function and pass in the two required arguments:
indexOf("woof", "o") //this would return 1

Javascript exercise that looks fine to me but its not working

The exercise is about identifying if all elements in an array are the same and return true if they are or false if they aren't. Below is the code & my logic behind writing the code.
function isUniform(array){
for(var i = array.length - 1; i>=0; i--){
if(array[i] !== array[i-1]){
return false;
}
}
return true;
}
Basically I want to start from the end of the array with the last element and check if its equal with the second-to-last element.If they're equal, the loop will subtract 1 from the "i" variable and the "if statement" will run again. The loop will stop when i reaches -1 and thats the point where every array element was checked and the loop should end, returning true. What am I doing / thinking wrong?
Thanks!
When i becomes 0, you are comparing arr[0] with arr[-1] which is wrong. Your checking condition should be i > 0.
The very last time it run, i is 0, so you're comparing array[0] with array[-1] which is incorrect. Your Boolean condition should be i > 0 so you avoid this issue:
function isUniform(array){
for(var i = array.length - 1; i > 0; i--){
if(array[i] !== array[i-1]){
return false;
}
}
return true;
}
You can use every method for a simplified solution.
const allEqual = arr => arr.every(x => arr[0] == x));
You could create a method that checks the array for your input using ArrayUtils.
public boolean contains(final int[] array, final int key) {
return ArrayUtils.contains(array, key);
}
Traveling so can't debug, but the last iteration of i will be 0 in your code and stop.

How to check if a string only contains chars from an array?

I try to check if a word (wordToCheck) only consists of letters from an array (letters) and also contains every letter in the array only as often (or rather not more times than they are in the array) as it actually is inside of the array.
Here are examples of what the desired function should return:
checkIfWordContainsLetters("google", ["a","o","o","g","g","l","e","x"]) === true
checkIfWordContainsLetters("google", ["a","o","g","g","l","e","x"]) === false
How can I make this code work?
function checkIfWordContainsLetters(wordToCheck, letters) {
var lettersToString = letters.toString();
var lettersTrimmed = lettersToString.replace(/,/gi, "?");
var regEx = new RegExp(lettersTrimmed, "gi");
if (wordToCheck.match(regEx)!== null) {
return true;
}
else return false;
}
You could use this ES6 function:
function checkIfWordContainsLetters(wordToCheck, letters){
return !letters.reduce((a, b) => a.replace(b,''), wordToCheck.toLowerCase()).length;
}
console.log(checkIfWordContainsLetters("google", ["a","o","o","g","g","l","e","x"]));
console.log(checkIfWordContainsLetters("google", ["a","o","g","g","l","e","x"]));
The idea is to go through each letter in the letters array, and remove one (not more!) occurrence of it in the given wordToCheck argument (well, not exactly in it, but taking a copy that lacks that one character). If after making these removals there are still characters left over, the return value is false -- true otherwise.
Of course, if you use Internet Explorer, you won't have the necessary ES6 support. This is the ES5-compatible code:
function checkIfWordContainsLetters(wordToCheck, letters){
return !letters.reduce(function (a, b) {
return a.replace(b, '');
}, wordToCheck.toLowerCase()).length;
}
console.log(checkIfWordContainsLetters("google", ["a","o","o","g","g","l","e","x"]));
console.log(checkIfWordContainsLetters("google", ["a","o","g","g","l","e","x"]));
As long as it is not the best solution for long strings for which using some clever regex is definitely better, it works for short ones without whitespaces.
function checkIfWordContainsLetters(word, letters){
word = word.toLowerCase().split('');
for(var i = 0; i < letters.length; i++) {
var index = word.indexOf( letters[i].toLowerCase() );
if( index !== -1 ) {
// if word contains that letter, remove it
word.splice( index , 1 );
// if words length is 0, return true
if( !word.length ) return true;
}
}
return false;
}
checkIfWordContainsLetters("google", ["a","o","o","g","g","l","e","x"]); // returns true
checkIfWordContainsLetters("google", ["a","o","g","g","l","e","x"]); // returns false

How can I rewrite the .length() property using slice()?

This is my assignment:
By now you should have worked with the length property of strings, e.g. "hello".length. Your task is to write a function called stringLength that accepts a string as a parameter and computes the length of that string; however, as you may have guessed, you are not allowed to use the length property of the string!
Instead, you'll need to make use of the string method called slice.
For our purposes, we can consider slice as taking one argument -- the index to begin slicing from, and returns a new string starting from that index onwards.
This is what I tried:
function stringLength(string){
var count = count++;
if(string.slice(0)){
return count}
return stringLength(string.slice(0,-1))
}
console.log(stringLength("game"))
I am trying to slice each character of the string back to start index, index 0, and then accumulate my count variable. I do not understand why my count variable is not accumulating.
An iterative proposal.
function stringLength(string) {
var count = 0;
while (string) {
string = string.slice(1);
count++;
}
return count;
}
console.log(stringLength("game"));
A recursive proposal.
function stringLength(string) {
return string ? 1 + stringLength(string.slice(1)) : 0;
}
console.log(stringLength("game"));
Hmm i tried to write code in the same format that you did.
function stringLength(str, count){
if(!str.slice(0)){
return count;
}
return stringLength(str.slice(0,-1), ++count)
}
console.log(stringLength("game", 0))
I'll point out the mistakes in your original code so that its easy to understand.
The recursion base case was incorrect. string.slice(0) will return
true if the string is non-empty, so use !string.slice(0)
The count value was not initialized and it wasn't being passed down
the recursion.
Your count variable is a separate variable for each function invocation, so it will always get the same value and not keep incrementing.
You could use this:
function stringLength(string){
return string ? 1 + stringLength(string.slice(0,-1)) : 0;
}
console.log(stringLength("game"))
A bit shorter would be to take out the first character instead of the last:
return string ? 1 + stringLength(string.slice(1)) : 0;
You really should try to figure it out yourself. Otherwise, are you really learning the subject?
function stringLength(string) {
if(!string) return 0;
var length = -1;
while(string.slice(length) !== string) --length;
return -length;
}
A variation taking into account your odd definition of slice():
function stringLength(string) {
var length = 0;
while(string.slice(length) !== "") ++length;
return length;
}
I guess you could try to use recursion like this:
function stringLength(string) {
if (string) {
return 1 + stringLength(string.slice(1))
} else return 0
}
function stringLength(string) {
var len = 0;
while (string) {
string = string.substring(1);
len++;
}
return len;
}
console.log(stringLength("boss"));
this works as well.

Checking if one element of an array's index is equal to the second element

I have this little script that will check if one element of an array (arr[0]) is equal to the second element of the array (arr[1]). However when it checks the following array I would expect it to return false, yet it returns true. so my questions are, why does this return true, and how can I fix it to return false like expected?
function mutation(arr) {
var elem0 = arr[0].toLowerCase();
var elem1 = arr[1].toLowerCase();
for(var x=0; x < elem1.length; x++){
check = elem0.indexOf(elem1[x]);
if(check === -1){
return false;
}
return true;
}
}
mutation(["hello", "hey"]); //returns true
you place the return true to soon
you need to place it after the for statement like so
function mutation(arr) {
var elem0 = arr[0].toLowerCase();
var elem1 = arr[1].toLowerCase();
for(var x=0; x < elem1.length; x++){
check = elem0.indexOf(elem1[x]);
if(check === -1){
return false;
}
}
return true;
}
mutation(["hello", "hey"]); //returns false
You're looping over a characters in a string (see what elem1 actually is), and therefore you get true because the first character of hey, which is h, is indeed found within the string hello.
If you want to wait for it to finish iterating over the whole string, use a boolean flag, and then return the value of that flag when the iterations are over.
However, seems you just want to compare the two elements:
return elem0 === elem1;
I have this little script that will check if one element of an array
(arr[0]) is equal to the second element of the array (arr[1])
It returns true since e is in both the elements hello and hey
Your code is essentially iterating over all the characters in the string.
You need to simply check
function mutation(arr) {
return arr[0].toLowerCase() == arr[1].toLowerCase();
}
The expression of this question has some logical flaws or at least some lacking points. Such as the given condition means that all the items in the array must be equal. If this is the case then just one tiny piece of instruction is sufficient
myArray.every(e => e == myArray[0])
var a = [1,1,1,1,1,1,1,1],
b = ["hello", "hey"];
document.write("<pre> a array :" + a.every(e => e == a[0]) + "</pre>");
document.write("<pre> b array :" + b.every(e => e == b[0]) + "</pre>");

Categories