![](/img/trans.png)
[英]How to get multiple matched values from the array object using javascript?
[英]How to match an array and get the most matched array using javascript
我正在嘗試將一個數組的數組與另一個數組以及我想要使用的兩個數組之間的最大匹配數組進行匹配。 但我無法得到確切的結果。我正在嘗試匹配最大匹配並檢索結果這里是 arrays 的數組
const urlArray = [
"https://example.com/rating",
"https://example.com/property",
"https://example.com/rating/on",
];
const urlArraySplit = urlArray.map((url) => {
return new URL(url).pathname.split("/");
});
console.log(urlArraySplit);//this gives an array of array
const url ='https://example.com/rating/on/45/45'
const array = url.split("/")
const urlArray = [ "https://example.com/rating", "https://example.com/property", "https://example.com/rating/on", ]; const url = "https://example.com/rating/on/45/45"; const domain = "example.com"; console.log(findMatch(url, domain)); function findMatch(url, domain) { const path = url.substring(domain.length + url.indexOf(domain) + 1, url.length); var urlForSearch = "https://" + domain; var mostMatch = []; const routes = path.split('/'); for (var i = 0; i < routes.length; i++) { var route = routes[i]; urlForSearch += `/${route}`; var result = urlArray.filter((url) => { return url.startsWith(urlForSearch); }); if (result.length > 1) { mostMatch = result; } else if (result.length === 1) { return result; } } return mostMatch; }
matchCount
方法是獲取 2 個字符串之間的數字匹配項。 用'/'分割並開始一一比較兩個數組單詞
closestMatch
方法是遍歷 urls 數組,計算匹配數,得到匹配數最大的 url。
const matchCount = (str1, str2) => { let count = 0; const arr1 = str1.split("/"); const arr2 = str2.split("/"); while (arr1.length > 0 && arr2.length > 0) { if (arr1.shift() === arr2.shift()) { count += 1; } } return count; }; const closestMatch = (arr, item) => { let matched_str = ""; let max_matches = 0; arr.forEach((str) => { const matches = matchCount(item, str); if (matches > max_matches) { max_matches = matches; matched_str = str; } }); return matched_str; }; const urlArray = [ "https://example.com/rating", "https://example.com/property", "https://example.com/rating/on", ]; const url = "https://example.com/rating/on/45/45"; console.log(closestMatch(urlArray, url));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.