![](/img/trans.png)
[英]how to get one string / value from an Array which has the same name but has a different type using JavaScript?
[英]How to Know if array has same letters as string
所以我一直試圖實現的是,如果我遍歷arr
和string
並且如果它們具有相同的字母,那么應該執行一些操作,例如 - 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
}
這是線性時間 O(n)。 檢查兩個項目是否具有相同的字符和相同的字符數。
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.