0

Hi I'm trying to figure out how to sort this. Below is a sample of my array.

product_sort_arr = [
  [{name:'Particle'},link:value}],
  [{name:'Bio-Part112',link:value}],
  [],
  etc  . . . 
];

I hope you can visualize the sample.

so far I have tried using and it's still not working. Still trying to fix this. Any help would be great

product_sort_arr.sort(function(a, b) {
        return a.name - b.name;
})

Expected return

product_sort_arr = [
  [{name:'Bio-Part112'},link:value}],
  [{name:'Particle',link:value}],
  [],
  etc  . . . 
];
Anton
  • 429
  • 4
  • 17
  • array is not symmetric. please write the exepected array – xkeshav Oct 09 '14 at 06:01
  • What are you expecting when you are making math operation (minus) on strings? Actually it's NaN. You need something else to compare with. Also, in sort function, `a` and `b` are arrays and they don't have `name`. – nikodz Oct 09 '14 at 06:07
  • see : http://stackoverflow.com/questions/6267329/how-to-sort-a-js-object-literal – xkeshav Oct 09 '14 at 06:21

2 Answers2

2

I am not sure what your array should be, but now it is defined with some errors. This example is working. I hope it will move you in the right direction.

var product_sort_arr = [
  [{name:'Particle', link:'value'}],
    [{name:'Bio-Part112',link:'value'}],
];

product_sort_arr.sort(function(a, b) {
  if (a[0].name > b[0].name) {
    return 1;
  }
  if (a[0].name < b[0].name) {
    return -1;
  }
  return 0;
});
    for (i=0;i<product_sort_arr.length;i++) {
        console.log(product_sort_arr[i][0].name);
}

Check on JSFiddle

Note that the array is an array of objects so you get the name with product_sort_arr[0][0].name and product_sort_arr[1][0].name

Barry
  • 3,683
  • 1
  • 18
  • 25
0

your array is not symmetric, i have created this demo it will sort the array based on name

var p = [
  [{name:'Particle',link:'valueA'}],
  [{name:'Bio-Part112',link:'valueB'}],
];
console.log(p);
p.sort(function(a,b) {
    return a[0].name > b[0].name;
});
console.log(p);
xkeshav
  • 53,360
  • 44
  • 177
  • 245