Fawad Mueed
Fawad Mueed

Reputation: 179

How to check if two strings contain same characters in Javascript?

I have two strings:

var a = 'ABCD';
var b = 'DEFG';

I need to compare these variables to check if there is not a common CHARACTER in the two strings.

So for this case return false (or do something...) because D is a common character in them.

Upvotes: 3

Views: 15046

Answers (6)

Armen Nersisyan
Armen Nersisyan

Reputation: 343

const _str1 = 'ABCD';
const _str2 = 'DEFG';

function sameLetters(str1, str2) {
  if(str1.length !== str2.length) return false;
  
  const obj1 = {}
  const obj2 = {}
 
 for(const letter of str1) {
    obj1[letter] = (obj1[letter] || 1) + 1
 } 
 for(const letter of str2) {
    obj2[letter] = (obj2[letter] || 1) + 1
 }
  
 for(const key in obj1) {
    if(!obj2.hasOwnProperty(key)) return false
    if(obj1[key] !== obj2[key]) return false
  }
  return true
}

sameLetters(_str1, _str2)

Upvotes: 0

AlpacaFur
AlpacaFur

Reputation: 192

This is obviously too late to matter to the original poster, but anyone else who finds this answer might find this useful.

var a = 'ABCD';
var b = 'DEFG';

function doesNotHaveCommonLetter(string1, string2) {
    // split string2 into an array
    let arr2 = string2.split("");
    // Split string1 into an array and loop through it for each letter.
    // .every loops through an array and if any of the callbacks return a falsy value,
    //     the whole statement will end early and return false too.
    return string1.split("").every((letter) => {
        // If the second array contains the current letter, return false
        if (arr2.includes(letter)) return false;
        else {
            // If we don't return true, the function will return undefined, which is falsy
            return true;
        } 
    })
}

doesNotHaveCommonLetter(a,b) // Returns false
doesNotHaveCommonLetter("abc", "xyz") // Returns true

Upvotes: 0

Tuomas H
Tuomas H

Reputation: 21

I was also searching for solution to this problem, but came up with this:

a.split('').filter(a_ => b.includes(a_)).length === 0

Split a into array of chars, then use filter to check whether each char in a occurs in b. This will return new array with all the matching letters. If length is zero, no matching chars.

add toUpperCase() to a & b if necessary

Upvotes: 2

samoan
samoan

Reputation: 98

So if it only duplicate strings in separate string arrays using .split(''), then I would sort the two string separately, and then do a binary search, start with the array of the shortest length, if the same length the just use the first one, and go character by character and search to see if it is in the other string.

Upvotes: 0

Fawad Mueed
Fawad Mueed

Reputation: 179

Thank you every one. I tried your solutions, and finally got this :

  • Merging my two strings into one
  • to Lower Case,
  • Sort,
  • and Join,
  • using Regex Match if the Final Concatenated string contains any repetitions,
  • Return 0 if no Repeat occur or count of repeats.

    var a; var b; 
    var concatStr=a+b;
    checkReptCharc=checkRepeatChrcInString(concatStr);
    function checkRepeatChrcInString(str){
    console.log('Concatenated String rec:' +  str);
    try{ return 
    str.toLowerCase().split("").sort().join("").match(/(.)\1+/g).length; }
    catch(e){ return 0; } 
     }
    

Upvotes: 4

samoan
samoan

Reputation: 98

You could merge the two strings then sort it then loop through it and if you find a match you could then exit out the loop.

I found this suggestion on a different stack overflow conversation:

var str="paraven4sr";
var hasDuplicates = (/([a-zA-Z]).*?\1/).test(str)    

So if you merge the strings together, you can do the above to use a regexp, instead of looping.

Upvotes: 4

Related Questions