ITConflux ITConflux - 1 year ago 77
Javascript Question

JavaScript: Sort an nested array

I have an nested array unsorted after sorting it should be sorted depending on 2nd item of sub-array

var unsorted = [["tag_17",0,4],["tag_18",13,18],["tag_435",6,11]];
var sorted = [["tag_18",13,18], ["tag_435",6,11], ["tag_17",0,4]];

Answer Source

var a = [
  ["tag_17", 0, 4],
  ["tag_18", 13, 18],
  ["tag_435", 6, 11]
];

a.sort(sortFunction);
console.log(a);

function sortFunction(a, b) {
  if (a[0] === b[0]) {
    return 0;
  }
  return (a[1] < b[1]) ? 1 : -1;
}

You can read the documentation about sort.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download