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.

1 Answer 1

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'));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.