Итак, я бы собрал все значения, используя .map
, а затем .reduce
, в объект в формате { city: count }
. Наконец, вы можете создать html элементов и вставить их в DOM.
// Extract the values to an array
let locations = $('.course-location').map((i, e) => $(e).data('value')).toArray();
let reducer = (a, c) => {
// If the city doesn't exist
a[c] === undefined ?
a[c] = 1 : // One occurrence, else
a[c] = a[c] + 1; // Increment count
return a;
}
let location_count = locations.reduce(reducer, {});
// Create HTML Elements
for (var place in location_count) {
$('.class-location').append(`<h4>${place}</h4><span>${location_count[place]}</span>`)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="course-location" data-value="Crowley, Texas"></div>
<div class="course-location" data-value="Denver, Colorado"></div>
<div class="course-location" data-value="Houston, TX"></div>
<div class="course-location" data-value="Denver, Colorado"></div>
<div class="course-location" data-value="Dallas, Texas"></div>
<div class="course-location" data-value="Crowley, Texas"></div>
<div class="class-location"></div>