Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

146
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda