Answer the question
In order to leave comments, you need to log in
Why doesn't comparing array elements work?
Good afternoon!
Please help me figure it out. I wrote a function, it compares 2 array elements (strings), determines whether all the letters from the second array are in the first array, if all - returns true. If there are other letters in the second array, it returns false.
Everything works, but, as they say, there is one point: comparing the arguments ["hello", "neo"] returns true. Against all common sense and against direct validation (see comments in code). What is the focus?
function mutation(arr) {
var arr1 = arr.splice(1,1);
var arr1 = arr1.join('').toLowerCase().split('');
var arr = arr.join('').toLowerCase().split('');
var x;
//console.log(arr.indexOf(arr1[i]));//проверка выдает -1, т.е. ключ, на который должен возвращаться false/
for(var i = 0; i < arr1.length; i++){
if(arr.indexOf(arr1[i]) === -1){
x = false;
}else if(arr.indexOf(arr1[i]) > -1){
x = true;
}
}
return x;
}
mutation(["hello", "neo"], "");
Answer the question
In order to leave comments, you need to log in
When the last letter, 'o', is checked, x becomes true, because there is such a letter in 'hello'. The minimum fix is to do this:
for(var i = 0; i < arr1.length; i++){
if(arr.indexOf(arr1[i]) === -1){
return false;
}
}
return true;
function mutation(arr) {
return Array.prototype.every.call(arr[1], (e) => ~arr[0].indexOf(e));
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question