Antonio Hazboun
Antonio Hazboun

Reputation: 27

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 a y in hello and I don't understand why.

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"]);

Upvotes: 0

Views: 80

Answers (3)

Highdown
Highdown

Reputation: 674

I would recommend using one of the code solutions suggested by user georg at Remove Duplicates from JavaScript Array.

For example, the function below could be used to sort each array (arr[0] and arr[1]) and remove duplicates.

Credit to user georg at the link above.

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

Upvotes: 0

Mirodil
Mirodil

Reputation: 2329

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.

Upvotes: 0

Srinivas ML
Srinivas ML

Reputation: 730

You are returning true even if one character is matched ,Try below code it checks if all characters are present or not

    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"]);

Upvotes: 1

Related Questions