Gaetan
Gaetan

Reputation: 37

look up if the characters in a string match the characters in a string array

I am trying to achieve something like this:

const word = "abracadabra" let usedCharacter = ["a", "b", "c", "d", "r"]

if word consists of the available usedCharacter return true

let usedCharacter = ["a", "b", "c", "d", "r", "z"] should also return true

let usedCharacter = ["b", "c", "d", "r", "z"] should return false

should i iterate through word with a for loop and compare every word(i) with the used characters or is there an more easy way?

Thanks for your thoughts!

Upvotes: 0

Views: 51

Answers (2)

DecPK
DecPK

Reputation: 25398

You can easily achieve this using splitting the word with each character and check if every character is there in usedCharacter or not.

const word = "abracadabra";
const usedCharacter = ["a", "b", "c", "d", "r"];

function hasAllUsedCharacters(word, used) {
  return word.split("").every((c) => usedCharacter.includes(c));
}

const result = hasAllUsedCharacters(word, usedCharacter);
console.log(result);

Alternate solution using Set

const word = "abracadabra";
const usedCharacter = ["a", "b", "c", "d", "r"];

function hasAllUsedCharacters(word, used) {
  const set = new Set(usedCharacter);
  const initialLength = set.size;
  word.split("").forEach((w) => set.add(w));

  return set.size === initialLength;
}

const result = hasAllUsedCharacters(word, usedCharacter);
console.log(result);

Upvotes: 0

Yair I
Yair I

Reputation: 1133

you can do this like this:

const word = "abracadabra";
let usedCharacter = ["a", "b", "c", "d", "r"];

let res = word.split('').filter(function(char) {
    return !usedCharacter.includes(char);
});
if(res.length == 0) {
     return true;
} else {
     return false;
}

this way you can know which characters are missing

good luck

Upvotes: 1

Related Questions