简体   繁体   中英

How to check if one element of an array matches another element in same array?

Very new to javascript so bear with me... I need to check one element of an array(arr[1]), which contains a string, against another element of the same array(arr[0]) to determine if any letters included in element arr[1] are included in arr[0]. Those letters can be in any order, upper or lower case, and don't have to occur the same number of times (ie arr[0]="hheyyy" and arr[1]="hey" is fine). This is what i have (which works) but I was curious if anyone has a better/more simple way of doing this? -thanks in advance.

   function mutation(arr) {
     //splits the array into two separate arrays of individual letters
      var newArr0 = arr.join('').toLowerCase().split('').slice(0,arr[0].length);
      var newArr1 = arr.join('').toLowerCase().split('').slice(arr[0].length);
      var boolArr = [];
     //checks each letter of arr1 to see if it is included in any letter of arr0
      for(var i = 0; i < newArr1.length; i++)
        boolArr.push(newArr0.includes(newArr1[i])); 
     //results are pushed into an array of boolean values
      if (boolArr.indexOf(false) !==-1) 
        return false; //if any of those values are false return false
      else return true;
    }

    mutation(["hello", "hey"]); //returns false

You could use a regular expression:

function mutationReg(arr) {
  return !arr[1].replace(new RegExp('['+arr[0].replace(/(.)/g,'\\\\$1')+']', "gi"), '').length;
}

This escapes every character in the second string with backslash (so it cannot conflict with regular expression syntax), surrounds it with square brackets, and uses that as a search pattern on the first string. Any matches (case-insensitive) are removed from the result, so that only characters are left over that don't occur in the second string. The length of the result is thus an indication on whether there was success or not. Applying the ! to it gives the correct boolean result.

This might not be the fastest solution.

Here is another ES6 alternative using a Set for good performance:

function mutation(arr) {
  var chars = new Set([...arr[0].toLowerCase()]);
  return [...arr[1].toLowerCase()].every (c => chars.has(c));
}

You can use Array.from() to convert string to an array, Array.prototype.every() , String.prototype.indexOf() to check if every charactcer in string converted to array is contained in string of other array element.

 var arr = ["abc", "cab"]; var bool = Array.from(arr[0]).every(el => arr[1].indexOf(el) > -1); console.log(bool); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM