I’m trying to sort the employees object array by age and i’m getting the following output:
[object Object],[object Object],[object Object],[object Object]
However, the code works fine when i just replace the employees array with an array of numbers like:
var points=[2,10,7,8]
Can someone tell me on where i’m going wrong? Thank you.
The following is my code:
<script type="text/javascript">
function sortFunc(){
var employees=[]
employees[0]={name:"George", age:32, retiredate:"March 12, 2014"}
employees[1]={name:"Edward", age:17, retiredate:"June 2, 2023"}
employees[2]={name:"Christine", age:58, retiredate:"December 20, 2036"}
employees[3]={name:"Sarah", age:62, retiredate:"April 30, 2020"}
employees.sort(function(a, b){
return a.age-b.age
// return a-b;
})
document.getElementById("disp").innerHTML=employees;
}
</script>
</head>
<body>
<div id="disp">Click the button below to sort.</div>
<button onclick="sortFunc()">Sort Now</button>
</body>
Sorting works fine.
The way you’re outputting it is incorrect.
Try to use a loop and than innerHTML to add it to the page.
Also you can define the object like that:
Cheers
G.