Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

297
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!