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, and the web.
If you enjoyed this article, you want to join his newsletter.

comments powered by Disqus