Isnor Creative
Isnor Creative Blog
Ruby, Ruby on Rails, Ember, Elm, Phoenix, Elixir, React, Vue

Feb 11, 2016

Ember.js – Sorting by an arbitray value

I recently came across a scenario where I had log events, some of which I needed to guarantee got sorted into a specific order based on an event type field. In my case, I always wanted an event with a “completed_session” event type to appear last in a list.

Normally with Ember you could do something as simple as this:

import Ember from 'ember';
const { computed } = Ember;

export default Ember.Component.extend({

  sortKeysForMilestones: ['insertedAt:asc’, ‘questionNumber:asc’],
  sortedMilestones: computed.sort(‘model.milestones’, 'sortKeysForMilestones)

});

This was’t working out for me in this case, because the timestamps were happening such that my completed session milestone was coming up second last.

It was very easy to implement a solution though using a custom sort function.

import Ember from 'ember';
const { computed } = Ember;

export default Ember.Component.extend({

sortedMilestones: computed.sort('model.milestones', function (a, b) { if (a.eventType === "completed_session") { return 1; } else if ((a.insertedAt < b.insertedAt) | (a.questionNumber < b.questionNumber)) { return -1; } return 0; });

});

˜


I am available for Ember consulting work – get in touch to learn more.

Gordon B. Isnor

Gordon B. Isnor writes about Ruby on Rails, Ember.js, Elm, Elixir, Phoenix, React, Vue and the web.
If you enjoyed this article, you may be interested in the occasional newsletter.

I am now available for project work. I have availability to build greenfield sites and applications, to maintain and update/upgrade existing applications, team augmentation. I offer website/web application assessment packages that can help with SEO/security/performance/accessibility and best practices. Let’s talk

comments powered by Disqus