Javascript Data Type How to - Sort an object array by property








Question

We would like to know how to sort an object array by property.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--  w  w  w.  j  a v a  2  s .c  o m-->
Array.prototype.keySort=function(key1)
{
    this.sort(function(a,b) {return (a[key1] > b[key1]) ? 1 : ((b[key1] > a[key1]) ? -1 : 0);} );
}
var a1 = [ 
    { key: 1, height : 100 },
    { key: 2, height: 700 },
    { key: 3, height: 200 }
];
a1.keySort("height");
document.writeln(JSON.stringify(a1));

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: