[英]Javascript How to identify if all elements of one array are present in another
I need to create a function to check if all the letters in the second string of a two string array are present in the first string. 我需要创建一个函数来检查两个字符串数组的第二个字符串中的所有字母是否都存在于第一个字符串中。 The function I wrote seems to work for most of the examples I tried with it but ["hello" , "hey"] returns true despite there not being ay in hello and I don't understand why. 我编写的函数似乎可以用在我尝试过的大多数示例中,但是[hello],“ hey”]返回true,尽管您好,而我也不知道为什么。
Here's my code: 这是我的代码:
function mutation(arr) {
arr[0] =arr[0].toUpperCase().split("");
arr[1] =arr[1].toUpperCase().split("");
for(i=0;i<arr[1].length;i++){
if(arr[0].indexOf(arr[1][i])>=0){
return true;
} else {return false;}}}
mutation(["hello", "Hey"]);
You are returning true even if one character is matched ,Try below code it checks if all characters are present or not 即使一个字符匹配,您也将返回true,请尝试以下代码,它检查所有字符是否存在
function mutation(arr) {
arr[0] = arr[0].toUpperCase().split("");
arr[1] = arr[1].toUpperCase().split("");
var count = 0;
for (i = 0; i < arr[1].length; i++) {
if (arr[0].indexOf(arr[1][i]) >= 0) {
count++;
}
}
return count === arr[1].length
}
mutation(["hello", "Hey"]);
here is one more efficient solution, it works only for lowercase letters. 这是一种更有效的解决方案,仅适用于小写字母。
(function(){ function charCode(str, i){ return str.charCodeAt(i) - 97; } function isMutation(a,b){ const aArr = new Uint8Array(26); const bArr = new Uint8Array(26); let i=0; let index = 0; while(i<a.length){ ++aArr[charCode(a, i)]; ++i; } i = 0; while(i<b.length){ ++bArr[charCode(b, i)]; ++i; } i = 0; while(i < 26){ if(!(aArr[i]===0 && bArr[i]===0 || aArr[i]>0 && bArr[i]>0)){ return false } ++i; } return true; } console.assert(isMutation('hello', 'oleh') === true); console.assert(isMutation('hello', 'hey') === false); })();
you can also compare sum of uniq chars in the both arrays, but in this case you have to add each letters only once. 您还可以比较两个数组中uniq字符的总和,但是在这种情况下,您只需将每个字母相加一次。
I would recommend using one of the code solutions suggested by user georg at Remove Duplicates from JavaScript Array . 我建议使用georg用户在“ 从JavaScript数组中删除重复项”中建议的代码解决方案之一。
For example, the function below could be used to sort each array (arr[0] and arr[1])
and remove duplicates. 例如,下面的函数可用于对每个数组(arr[0] and arr[1])
进行排序并删除重复项。
Credit to user georg at the link above. 在上面的链接中感谢georg用户。
function uniq(a) {
return a.sort().filter(function(item, pos, ary) {
return !pos || item != ary[pos - 1];
})
}
Once you have sorted/removed duplicates, you can test to see if the two returned strings are equal or not. 对重复项进行排序/删除后,可以测试一下两个返回的字符串是否相等。
Hello => EHLO, and Hey => EHY 你好=> EHLO,嘿=> EHY
EHLO !== EHY H!===
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.