Jim
Jim

Reputation: 420

Sort model based on defined order

So what I'm setting out to do is generally gross and horrible, but I have to work with the data I'm given.

I have a questionnaire that is the same for all users. It has the following attributes: id, name, required. In the database, the name fields appear in this order:

cell_phone
city
date_of_birth
email
first_name
graduation_year
last_name
phone
state
coach
name

This order is based on their ids. I need them to appear on the page grouped in a way that is more intuitive, i.e.:

first_name
last_name
email
phone
city
state
zip
...

In my route, I simply set the model:

userId = App.Session.get("userId")
@store.find("questionnaire", userId: userId)

Is there a way to either map over the array that comes back from the model and basically hard code this order or sort the model in the controller to match a given order based on name or index?

Upvotes: 0

Views: 29

Answers (1)

dwickern
dwickern

Reputation: 3519

You can create an array with the order you want, then sort by the item's index:

var order = [
    'first_name',
    'last_name',
    'email',
    'phone',
    'city',
    'state',
    'zip'
];

questions.sort(function(a, b) {
    return order.indexOf(a.name) - order.indexOf(b.name);
});

You could put that logic into a computed property or map the data when find completes

Upvotes: 1

Related Questions