0

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:

  1. Sort alphabetically by name
  2. Sort by the GPA achieved in 2010
  3. Sort by the GPA achieved in 2011
  4. Add new users to the list iff their name isn't already on it.

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.

Community
  • 1
  • 1
Richard
  • 31,629
  • 29
  • 108
  • 145

1 Answers1

1

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'));
qiao
  • 17,941
  • 6
  • 57
  • 46