Home > Enterprise >  how to sort nested array in javascript
how to sort nested array in javascript

Time:03-08

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);
}

CodePudding user response:

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}

CodePudding user response:

    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!

CodePudding user response:

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

CodePudding user response:

You need for this two forEach() loops and one sort().

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

const n = []
list.forEach(i => i.item.forEach(p => {
  n.push(p.price)
}))

console.log('sorted array: ',n.sort())

CodePudding user response:

flatMap is a better solution to this kind of problem

let liMap = list.flatMap(x => [x.item]).flat().flatMap(y => [y.price])
liMap.sort().map(e => {
    console.log(`price:${e}`)
})
  • Related