看到这篇文章How can i get most repeated value from Array in javascript
我是jquery的新手,我想知道如果在 id 或 class div中声明了数组值,该如何获取数组值?
<p>#1 - Rate: <span class="score" id="score1"> 5</span></p>
<p>#2 - Rate: <span class="score" id="score2"> 5</span></p>
<p>#3 - Rate: <span class="score" id="score3"> 5</span></p>
<p>#4 - Rate: <span class="score" id="score4"> 5</span></p>
<p>#5 - Rate: <span class="score" id="score5"> 5</span></p>
这是输出,看起来像:
<div id="totalScore">55555</div>
我通过获得5项商品的价格来做到这一点
jQuery("#totalScore").append(jQuery(".list1").text());
在上面的文章中,值位于数组内部
var arr = [{
values: "Number of pips"
}, {
values: 4
}, {
values: 4
}, {
values: 4
}, {
values: 5
}, {
values: 2
}, {
values: 6
}, {
values: 6
}, {
values: 5
}];
var uniqs = {};
for (var i = 0; i < arr.length; i++) {
uniqs[arr[i].values] = (uniqs[arr[i].values] || 0) + 1;
}
var max = {
val: arr[0],
count: 1
};
for (var u in uniqs) {
if (max.count < uniqs[u]) {
max = {
val: u,
count: uniqs[u]
};
}
}
alert(max.val);
如何这样转换?通过仅获取 id =“ totalScore” 或 .list1 中的值?
答案 0 :(得分:1)
用.score
遍历每个each
,从而增加对象中的关联值。然后,遍历对象的entries
,标识具有最大值的对象,并获取其键(通过访问条目的[0]
索引):
const counts = {};
$('.score').each((_, span) => {
const num = span.textContent.trim();
counts[num] = (counts[num] || 0) + 1;
});
console.log(
Object.entries(counts).reduce((a, item) => (
item[1] > a[1]
? item
: a
), [,0])[0]
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>#1 - Rate: <span class="score" id="score1"> 5</span></p>
<p>#2 - Rate: <span class="score" id="score2"> 5</span></p>
<p>#3 - Rate: <span class="score" id="score3"> 3</span></p>
<p>#4 - Rate: <span class="score" id="score4"> 4</span></p>
<p>#5 - Rate: <span class="score" id="score5"> 5</span></p>
<p>#6 - Rate: <span class="score" id="score6"> 4</span></p>