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

295
Vistas
how to sort nested array in javascript

im trying to sort this type of array and i have give the expected output below can anyone tell me how i can do that i know the single array sort but dont know the nested one can anyone help me...

var list = [
{name: "Bob" , item : [ {price:500},{price: 302} ]}, 
{name: "Tom" ,item : [  {price: 200} ,{price: 600}] },
 
];
expected output// price:200
              // price:302
              // price:500
              // price:600

//tried something for normal array what to do for this type of array

list.sort(function(a, b) {
return ((a.name < b.name) ? -1 : ((a.name == b.name) ? 0 : 1));
});

for (var i = 0; i<list.length; i++) {
alert(list[i].name + ", " + list[i].age);
}

​

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can use underscore.

_.chain(list).map((item) => item.item).flatten().pluck('price').sort().value()

Output:

[200, 302, 500, 600]

Or if you want to keep the keys:

_.chain(list).map((item) => item.item).flatten().sort((a,b) => a.price - b.price).value()

Output:

0: {price: 200}, 1: {price: 302}, 2: {price: 500}, 3: {price: 600}
about 4 years ago · Juan Pablo Isaza Denunciar

0

var list = [
  { name: "Bob", item: [{ price: 500 }, { price: 302 }] },
  { name: "Tom", item: [{ price: 200 }, { price: 600 }] },
];

let sortThePrices = [];

list.forEach((e) => {
  e.item.forEach((prop) => {
    sortThePrices.push(prop.price);
  });
});

sortThePrices.sort((a, b) => a - b);

sortThePrices.forEach((price) => {
  console.log("Price: " + price);
});

I tried to make this solution to problem easy to understand, I hope this helps

about 4 years ago · Juan Pablo Isaza Denunciar

0

    var list = [
      {name: "Bob" , item : [ {price:500},{price: 302} ]}, 
      {name: "Tom" ,item : [  {price: 200} ,{price: 600}] },
    ];

    const compare = ( a, b ) => {
      if ( a.price < b.price ){
        return -1;
      }
      if ( a.price > b.price ){
        return 1;
      }
      return 0;
    }

    list.map(val => val.item.sort(compare)) 
    console.log("list: ", list)

Hope this works for you!

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