0

Saw this article How can i get most repeated value from Array in javascript

I am a newbie in jquery, I would like to know if how can I get the array values if it is declared inside an id or 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>

This is the output looks like:

<div id="totalScore">55555</div>

I did this by getting the rates of 5 items

jQuery("#totalScore").append(jQuery(".list1").text());

In the article above the value is inside an array

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);

How to convert it like this? By getting only the value in id="totalScore" or .list1?

Sreekanth
  • 3,110
  • 10
  • 22
Raissa Ricarde
  • 108
  • 1
  • 11
  • Possible duplicate of [How can i get most repeated value from Array in javascript](https://stackoverflow.com/questions/25304109/how-can-i-get-most-repeated-value-from-array-in-javascript) – Code_Ninja Sep 06 '18 at 05:28

1 Answers1

1

Iterate over each .score with each, incrementing the associated value in an object. Then, iterate over the object's entries, identify the one with the maximum value, and get its key (by accessing the [0] index of the entry):

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>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320