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

296
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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