Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
Sort Numbers Numerically In a Div

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.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You're pushing a single string to your array with $(this).text(), not the individual values. Split the string with textArray = $(this).text().split(',');

Example:

let textArray = [];
$('.class-numbers').each(function() {
  textArray = $(this).text().split(',');
  textArray.sort(function(a, b) {
    return a - b;
  });
  console.log(textArray);
  $(this).text(textArray.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">9, 8, 7, 6, 5, 4, 3, 2, 1</div>
<div class="class-numbers">55, 11, 76, 2, 14</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

Based on your requirements, which you have clarified in your comments, you want to:

  1. Perform sorting of comma-separated numbers in each div.class-numbers individually
  2. 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>

about 4 years ago · Juan Pablo Isaza Relatório

0

Try to split the text into elements before you sort them.

textArray = $(this).text().split(', ')

You might want to convert them to numbers too.

textArray = $(this).text().split(', ').map(it => parseInt(it))
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda