How to re-render the sorted array elements

I am trying to build a todo app. I want the todos to be in the order of their priority. Also, there are buttons with which we can increment/decrement the priority of a todo item.

import Component from ‘@ember/component’; import { computed } from ‘@ember/object’;

export default Component.extend({ tagName: “”, todos: computed(‘todos.@each.priority’, function(){ return this.todos.sortBy(‘priority’); }) });

This is how I tried to sort the todos. But this is not working.

hi @VYSHNAV_RAJ_S, welcome! At first glance your code looks fine except for one thing: the computed property name appears to be the same as its dependent property. If todos is being passed into this component it’s probably overwriting the computed property that you’ve defined and therefore never actually computing the computed property meaning it won’t be sorted.

Typically you’d do something like this:

export default Component.extend({
  tagName: “”,
  sortedTodos: computed(‘todos.@each.priority’, function(){
    return this.todos.sortBy(‘priority’);

That way the computed property name describes what the property is doing. So todos is the dependent property and sortedTodos would be the sorted version.

Alternatively you could do this:

import { sort } from '@ember/object/computed';

export default Component.extend({
  tagName: “”,
  todosSortDef: Object.freeze(['priority']),
  sortedTodos: sort('todos', 'todosSortDef'),
1 Like

Thankyou. That worked