I’m using the following code/data to display a list of our top-earning students in each House.
The data

Attachment 1: User_Info is an array of Objects

Attachment 2: User_Info is an array of Objects such as this

Attachment 3: Database_Info is an Object like this
The code
HPAnalysisObject.dispHPTotals = function(User_Info, Database_Info) {
// See attachments 1 and 2
console.log(User_Info);
// See attachment 3
console.log(Database_Info);
// "label" is just a text title, like "Eagles"
var html = '<h2>' + HPAnalysisObject.label + '</h2>' +
// "TotalPoints" is an integer figure
'<div id="total">' + Database_Info.TotalPoints + '</div>';
// create the table to display
html += '<table><tr><th class="name">Name</th><th class="points">Points</th></tr>';
// use "for, in" to access the value of the object key (which is the user's ID)
for (var id in Database_Info.UserDetails) {
html += '<tr>';
for (var i = 0; i < User_Info.length; i++) {
if (User_Info[i].id == id) {
// if the User_Info and Database_Info objects match up on the User's ID, add table cells to our html variable
html += '<td class="name">' + User_Info[i].firstname + ' ' + User_Info[i].surname + '</td><td class="points">' + Database_Info.UserDetails[id] + '</td>';
}
}
html += '</tr>';
}
html += '</table>';
$('div#display').html(html);
};
The problem
Oddly, in Firefox, these students display in the correct numerical order, as the students are received from my PHP script.
However, in Google Chrome and Internet Explorer, they appear in a seemingly-random order!
My first thought was to order the object, but having read a few questions on here, it seems like ordering objects isn’t the best practice.
Can I rewrite this code so that I display the same tabular data – just in the right order on every browser?
Thanks in advance,
In most languages, you cannot assume that object attributes occur in any particular order.
One solution might be to add an accessor to each entry in UserDetails such as:
UserDetails={
ID:{
accessor:1,
id: ID
}
}
And then sort the records on UserDetails[ID].accessor.
Another might be to construct UserDetails as an array of elements which encode key values as “key:value”, splitting each retrieved elements on /:/ as in:
[
“90030:87”
…
]
EDIT
Assuming
where i is the accessor, you can create a sorted array of objects using
which extracts keys from userDetails, creates an array of the keyed elements via map and sorts the resulting elements by their accessor value such that
will print to the console: