I’m trying to sort numbers in a div in numerical order. But although the code looks ok, it’s just not working. So I’m seeing if anyone has any ideas?
On the page there are multiple divs on a page in this format, all with the same class name.
<div class="class-numbers">14, 16, 18, 25, 3, 38, 41, 9</div>
I’m trying to sort these numbers, in numerical order on page load. So I have stored them in an array and tried doing the .sort() function. But still hasn’t worked.
$(function() {
let textArray = [];
$('.class-numbers').contents().each(function () {
textArray.push($(this).text());
});
textArray.sort(function(a, b) {
return a - b;
});
console.log(textArray);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="class-numbers">14, 16, 18, 25, 3, 38, 41, 9</div>
The console log seems to console log the array of each div with class-numbers. But doesn’t seem to sort them numerically?
Any help is appreciated.
>Solution :
Based on your requirements, which you have clarified in your comments, you want to:
- Perform sorting of comma-separated numbers in each
div.class-numbersindividually - Overwrite the text content of each div with the newly sorted numbers
It is pretty straightforward: you simply use .text() and pass a function to it, which will return the sorted array of numbers. .text() accepts a function and will use the return value to set the inner text of the element.
This is one of the "magical" things about jQuery, is that .text(), like many other methods, implicitly loops through the collection: you don’t even need to use .each() first. These methods operates with sets of matched elements in mind, emphasis my own:
Set the content of each element in the set of matched elements to the specified text.
This gives us the code of the following nature:
$('.class-numbers').text(function(_i, text) {
return text.split(',').sort(function(a, b) {
return a - b;
}).join(',');
});
If you are familiar with ES6 though, we can squash all of this into a one-liner (sacrificing some readability, and loss of reference to this, which you will not need in this case anyway):
$('.class-numbers').text((_,t) => t.split(',').sort((a,b) => a-b).join(', '));
See proof-of-concept below:
$('.class-numbers').text((_,t) => t.split(',').sort((a,b) => a-b).join(', '));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="class-numbers">14, 16, 18, 25, 3, 38, 41, 9</div>
<div class="class-numbers">73, 16, 37, 22, 1</div>
There is always of course a native JS solution without needing jQuery 😉
document.querySelectorAll('.class-numbers').forEach(el => {
el.textContent = el.textContent
.split(',')
.sort((a,b) => a-b)
.join(', ');
});
<div class="class-numbers">14, 16, 18, 25, 3, 38, 41, 9</div>
<div class="class-numbers">73, 16, 37, 22, 1</div>