简体   繁体   English

如何知道数组是否与字符串具有相同的字母

[英]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" }所以我一直试图实现的是,如果我遍历arrstring并且如果它们具有相同的字母,那么应该执行一些操作,例如 - if ("both string and array have the same letters"){ "some action" }

const word = "hello";

const arr = ["o", "l", "e", "h"];
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
}

Here is with Linear time O(n).这是线性时间 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"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM