so what I have been trying to acheive is that if I iterate over arr
and string
and if they have the same letters then some action should be perfomed, for example - if ("both string and array have the same letters"){ "some action" }
const word = "hello";
const arr = ["o", "l", "e", "h"];
CodePudding user response:
const word = "hello";
const arr = ["o", "l", "e", "h"];
const uWord = [...new Set(word)].sort().join()
const uArr = [...new Set(arr)].sort().join()
if (uWord === uArr) {
// do something
}
CodePudding user response:
Here is with Linear time O(n). Check whether both items has same chars and same chars count.
const isMatch = (arr, word, track = {}) => {
arr.forEach((char) => (track[char] = (track[char] ?? 0) 1));
[...word].forEach((char) => (track[char] = (track[char] ?? 0) - 1));
return !Object.values(track).some((val) => val < 0);
};
console.log(isMatch(["o", "l", "e", "h"], "hello"));
console.log(isMatch(["o", "l", "e", "h", "l"], "hello"));
console.log(isMatch(["o", "o"], "lo"));