javascript - 获取逗号后出现最多的文本字符串,用于任何目的
问题描述
我想用 Jquery 在这个 HTML 中的“,”之后获取下面这段代码中出现次数最多的文本。在这种情况下,文本将返回“Bothell”。我该怎么做呢?
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Bothell</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Bellevue</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Kirkland</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Monroe</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Bothell</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Bothell</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Bothell</a>
从下面的用户那里尝试了此代码,但不起作用:
let As = document.querySelectorAll("a.address");
let towns = new Map();
for(let a of As)
{
let town = a.textContent.split(',')[1].trim()
if(towns.has(town))
{
towns.set(town, towns.get(town)+1)
}
else
{
towns.set(town, 1);
}
}
let most = [...towns.entries()].sort((a, b) => b[1] - a[1])[0];
if ($("a.address").length) {
var signupText = (most);
$(".rg-modal-signup h2").text('Keep searching ' + signupText + ' real estate.');
} else {
var signupText = '';
$(".rg-modal-signup h2").text('Keep searching for your dream home.');
}
解决方案
你必须在这里做多件事:
- 提取名称
- 计算出现次数
- 获得结果最高的那个。
这是您可以根据上面的输入使用的快速代码。请注意,这不考虑多次出现逗号,但我认为您已经可以调整接下来需要的内容。:)
const data = `<a href="/search/details/50/1/" class="address">9207 Odin Wy, Bothell</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Bellevue</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Kirkland</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Monroe</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Bothell</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Bothell</a>
<a href="/search/details/50/1/" class="address">9207 Odin Wy, Bothell</a>`;
const anchors = data.split('\n');
const getName = (row) => {
const index = row.indexOf(',');
const commaOffset = 2;
const suffixOffset = 4;
const length = row.length;
return row.substring(index + commaOffset, length - suffixOffset);
}
const names = anchors.map(getName);
const counts = names.reduce((group, name) => {
if (!group[name]) {
group[name] = 1;
} else {
group[name]++;
}
return group;
}, {});
const entries = Object.entries(counts);
const sorted = entries.sort((a, b) => b[1] - a[1])
const hightestCount = sorted.shift();
console.log(hightestCount)
这应该给你:
[ 'Bothell', 4 ]
你知道之后该怎么处理它。祝你好运!
推荐阅读
- css - 无法将 ADC 设置为完全响应
- c# - 如何为 (Xamarin) 跨平台 .NET 标准库创建单元测试和分析代码覆盖率
- android - 无法使用 TypeSafeMatcher
- haskell - Haskell 图:方向固定的箭头
- python - 如何解决这部分程序中的这个关键错误
- algorithm - 在棋盘上移动 N 个国王
- jsf - 问题 Primefaces + JSF 这个 XML 文件似乎没有任何与之关联的样式信息
- c# - 一个单元格中有多行的 SQL 子字符串问题
- steam - Steam API/JSON 中的物品买卖订单
- reactjs - Stackblitz 错误:找不到包:firebase