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

190
Vistas
How to sort an array of object by a specific field Javascript

I have an array containing multiple objects with multiple fields, and I'm trying to sort the array in decending order from the largest "Views" value to the lowest. but when I run my code it outputs a few in order, but the majority are random. There are a lot more array rows in my project if that could be affecting it.

list = [{title: "Test1", views: "25"}, {title: "Test2", "105"}, {title: "Test3", views: "12"}]
var len = list.length - 1;
list.sort(function (a, b) {
    return a.views.localeCompare(b.views) || b.views - a.views;
});
for(var x = 0; x < len; x++) {
    displayFunc(list[x].title, list[x].views);
}

Desired output:

{title: "Test2", views: "105"}, {title: "Test1", "25"}, {title: "Test3", views: "12"}
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

As mentioned in the comments, you dont need a localecompare here:

const list = [{title: "Test1", views: "25"}, {title: "Test2", views: "105"}, {title: "Test3", views: "12"}]

console.log(list.sort((a,b)=>{
    return  b.views - a.views
}));

about 4 years ago · Juan Pablo Isaza Denunciar

0

You have some errors in your code. I corrected your version and give you a somewhat better, more modern version.

const list = [{title: "Test1", views: "25"}, {title: "Test2", views: "105"}, {title: "Test3", views: "12"}];
var len = list.length;
const list_sorted = list.sort(function (a, b) {
    return parseInt(b.views, 10) - parseInt(a.views, 10);
});
for(var x = 0; x < len; x++) {
    console.log(list[x].title, list[x].views);
}

/// Better
list
  .map(el => ({ ...el, views: parseInt(el.views, 10) }))
  .sort((a,b) => b.views - a.views)
  .forEach(el => console.log(el.title, el.views));

about 4 years ago · Juan Pablo Isaza Denunciar

0

We can use any key available in object to sort. As per your requirement, 'view' is used here,

const list = [{title: "Test1", views: "25"}, {title: "Test2", views: "105"}, {title: "Test3", views: "12"}]

console.log(list.sort((a, b) => b.views - a.views));
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