JavaScript to check if string has at least three characters that are in another variable
Asked Answered
N

9

9

I have a variable activeUserName and a variable manager1.

How can I check if activeUserName contains at least three characters, that are in manager1? (The position of those characters doesn't matter)

For example in the following case, it should return true, because the characters 'J', 'o' and 'e' are inside manager1.

var activeUserName = "JohnDoe100";
var manager1 = "JYZALoe999";

Right now I'm using the indexOf method and only look at characters in certain positions which is why I want to change that:

if (isEditor == false){
    if (((activeUserName.indexOf(manager1.charAt(0)) !== -1)  && (activeUserName.indexOf(manager1.charAt(2)) !== -1)) || (activeUserName.indexOf(manager1.charAt(4)) !== -1)){
        // doSth();
    } else if (((activeUserName.indexOf(manager2.charAt(0)) !== -1)  && (activeUserName.indexOf(manager2.charAt(2)) !== -1)) || (activeUserName.indexOf(manager2.charAt(4)) !== -1)){
        // doSth();
    } else {
        // doSth();
    }
}

I read about Regex, but I'm not sure if this can be applied here.

Any help is appreciated!

Nurserymaid answered 7/8, 2020 at 15:1 Comment(0)
S
11

Combining .split() with .filter() you can trasform activeUserName in array and filter each char against the string manager1:

var activeUserName = "JohnDoe100";
var manager1 = "JYZALoe999";

var howMany = activeUserName.split('').filter(function(e, i, a) {
    return (manager1.indexOf(e) != -1);
}).length;

console.log('The number of chars in common is: ' + howMany);
Sonya answered 7/8, 2020 at 15:11 Comment(0)
C
2

var activeUserName = "JohnDoe100";
    var manager1 = "JYZALoe999";
    const arr1 = [...activeUserName];
    const arr2 = [...manager1];
    let count = 0;
    for (let i = 0; i<arr1.length; i++) {
      if (arr2.indexOf(arr1[i]) !== -1) count++;
    }
if(count >= 3)
  console.log(`string b 3 same values of string b`);
Coleville answered 7/8, 2020 at 15:13 Comment(0)
P
1

i think this approach is better, because we dont have to create a new array with split('')

 var activeUserName = "JohnDoe100";
        var manager1 = "JYZALoe999";
        let count = ""
        for (let letter of activeUserName) {
            if (manager1.indexOf(letter) > -1 && status.indexOf(letter) == -1)
                count = count + letter
        }
console.log('Characters in common',count);
console.log('Length',count.length);
Patrizio answered 7/8, 2020 at 15:13 Comment(0)
I
1

There can be multiple conditions associated with the question like two occurrences of the same character should be counted as 1 or 2, should uppercase and lowercase character be treated as same or not, etc. I'd just leave this below code-snippet so that you get the gist of the final solution. Any condition on top of that, you can add it yourself.

var activeUserName = "JohnDoe100";
var manager1 = "JYZALoe999";

let count = 0;

[...activeUserName].forEach(char1 => {
    [...manager1].forEach(char2 => {
        // add all your conditions here
        if(char1 === char2)
            count++;
    });
});

console.log(count);

The above code will output the number of characters which are common in both the strings.

Isbell answered 7/8, 2020 at 15:14 Comment(0)
D
1

Split the check-string in an array from chars. Iterate through it if a char is contained in the str and sum this.

var activeUserName = "JohnDoe100";
var manager1 = "JYZALoe999";


function check3Chars(str, check) {
    let count = 0;
    check.split('').forEach( char => {
        if (str.indexOf(char)!=-1) {
            count++;
        }
    });
    return count>=3;
};

console.log(check3Chars(activeUserName, manager1))
Dup answered 7/8, 2020 at 15:14 Comment(0)
J
1

Here is the code (ES5-compatible version). It should be more performant than other answers because it stops after 3 characters are found:

var activeUserName = "JohnDoe100";
var manager1 = "JYZALoe999";

var matchedCharacters = [];
var activeUserNameArray = activeUserName.split('');
for (var i = 0; i < activeUserNameArray.length && matchedCharacters.length < 3; i++) {
  if (
    manager1.indexOf(activeUserNameArray[i]) > -1 // check if both strings include the character
    && matchedCharacters.indexOf(activeUserNameArray[i]) === -1 // exclude duplicates, you can remove this condition if you want to count duplicates
  ) {
    matchedCharacters.push(activeUserNameArray[i]);
  }
}

console.log(matchedCharacters.length);
if (matchedCharacters.length >= 3) {
  // the strings have at least 3 common characters
} else {
  // the strings have less than 3 common characters
}

Here is an ES6 version:

const activeUserName = "JohnDoe100";
const manager1 = "JYZALoe999";

const matchedCharacters = [];
for (const char of activeUserName) {
  if (matchedCharacters.length >= 3) break;
  if (
    manager1.includes(char) // check if both strings include the character
    && !matchedCharacters.includes(char) // exclude duplicates, you can remove this condition if you want to count duplicates
  ) {
    matchedCharacters.push(char);
  }
}

console.log(matchedCharacters.length);

if (matchedCharacters.length >= 3) {
  // the strings have at least 3 common characters
} else {
  // the strings have less than 3 common characters
}
Jarmon answered 7/8, 2020 at 15:16 Comment(0)
O
1

Code

// Format the string for easier comparison checking
const prepareString = (str) => str.split("").map((str) => str.toLowerCase());

export function similarCharacters(subject, test) {
  // Prepared subject string
  const left = prepareString(subject);

  // Prepared test string
  const right = prepareString(test);
  // Map over the subject with a number as the initial value, this will be our count
  return left.reduce((acc, curr) => {
    // acc is the current count value
    // curr is the current letter from the subject

    // If the right string has an occurrence of the current letter add 1 to the counter
    if (right.indexOf(curr) > -1) {
      return acc + 1;
    }
    return acc;
  }, 0 /* our initial counter */);
}

Unit test

describe("similarCharacters", () => {
  it.each([
    ["hello", "yellow", 4],
    ["JYZALoe999", "JohnDoe100", 3]
  ])("%s and %s have %p similar characters", (left, right, expected) => {
    expect(similarCharacters(left, right)).toEqual(expected);
  });
});

For your use case:

const activeUserName = "JohnDoe100";
const manager1 = "JYZALoe999";

const similarCount = similarCharacters(manager1, activeUserName)
if(similarCount >= 3){
 // do something
}

CodeSandbox here: https://codesandbox.io/s/purple-tree-ni8xu?file=/src/similarCharacters.js

Occultation answered 7/8, 2020 at 15:21 Comment(0)
S
1

There are already some great answers, just wanted to join the party with a one liner that is not too hacky or unreadable.

const a = "JohnDoe100";
const b = "JYZALoe999";

const total = [...b].reduce((count, char) => count + (a.includes(char) ? 1 : 0), 0);

It does have the benefit of not creating additional variables except for the total which is what you actually need.

Stroll answered 8/8, 2020 at 12:10 Comment(1)
That's amazing. Thanks for sharingNurserymaid
S
1

Use For loop with break and Use includes()

To be clean, make a function that will do the job.

To be efficent use break when you find 3 match chars.

Prefer not to use var, use const and let.

const areStringsMatchCharsMoreThen2 = (stringA, stringB) => {
  let count = 0;
  for (let i = 0; i < stringB.length; i++) {
    if (count === 3) break;
    if (stringA.includes(stringB.charAt(i))) count++;
  }
  return count === 3;
}

const activeUser = "JohnDoe100";
const manager = "JYZALoe999";

const areStringsMatchCharsMoreThen2 = (stringA, stringB) => {
  let count = 0;
  for (let i = 0; i < stringB.length; i++) {
    if (count === 3) break;
    if (stringA.includes(stringB.charAt(i))) count++;
  }
  return count === 3;
}

console.log(areStringsMatchCharsMoreThen2(activeUser, manager));
console.log(areStringsMatchCharsMoreThen2('ABC', 'def'));
Sallie answered 14/8, 2020 at 14:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.