Reputation: 32959
I have the following information:
Name, GPA 2010, GPA 2011
Adam, [2010, 3.4], [2011, 3.9]
Ben, [2010, 3.4], [2011, 3.9]
Charlie, [2010, 3.4], [2011, 3.9]
I'd like to be able to do the following:
What is the most economical JavaScript data structure to use for this sort of sorting?
Currently I have this:
var grades = {
'Adam': [[2010, 3.4], [2011, 3.9]],
'Ben' : [[2010, 3.4], [2011, 3.9]],
'Charlie' : [[2010, 3.4], [2011, 3.9]] };
This makes it easy to achieve point 4 (if (name in grades === false)
) and reasonably easy to achieve point 1, but quite fiddly to achieve point 2 or 3.
Upvotes: 0
Views: 111
Reputation: 18229
Consider:
var grades = [
{
'name': 'Adam',
'2010': 3.4,
'2011': 3.9
},
{
'name': 'Ben',
'2010': 3.4,
'2011': 3.9
}
];
to sort:
function compareNames(a, b) {
var nameA = a.name.toLowerCase( );
var nameB = b.name.toLowerCase( );
if (nameA < nameB) {return -1}
if (nameA > nameB) {return 1}
return 0;
}
function compareGPAs(year) {
return function(a, b) {
return a.year - b.year;
}
}
// sort by name
grades.sort(compareNames);
// sort by GPA of 2010
grades.sort(compareGPAs('2010'));
Upvotes: 1