Anton
Anton

Reputation: 429

Sort Objects in 2nd level array

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  . . . 
];

Upvotes: 0

Views: 53

Answers (2)

Barry
Barry

Reputation: 3733

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

Upvotes: 2

xkeshav
xkeshav

Reputation: 54050

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

Upvotes: 0

Related Questions