Karan Rajput
Karan Rajput

Reputation: 75

How to Know if array has same letters as string

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

Upvotes: 1

Views: 608

Answers (2)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

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

Upvotes: 0

ptvty
ptvty

Reputation: 5664

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
}

Upvotes: 1

Related Questions