1

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"];
4
  • arr.every(e => word.includes(e)) Commented Jul 29, 2022 at 19:45
  • Use Set with array.every() Commented Jul 29, 2022 at 19:46
  • 3
    Define 'same letters' - does every character of word have to be in arr, and every character in arr have to be in word? Or just in one direction? Commented Jul 29, 2022 at 19:46
  • 2
    this is quite a fun little problem. Why ask stackoverflow for some one-liner when you could write a clever little algorithm yourself! Commented Jul 29, 2022 at 19:53

2 Answers 2

1
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
}
Sign up to request clarification or add additional context in comments.

1 Comment

I'd argue it's the shortest and cleanest solution.
0

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"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.