Function

Module: @ember/object
import { sort } from '@ember/object/computed';
itemsKey
String
additionalDependentKeys
Array
optional array of additional dependent keys
sortDefinition
String or Function
a dependent key to an array of sort properties (add `:desc` to the arrays sort properties to sort descending) or a function to use when sorting
returns
ComputedProperty
computes a new sorted array based on the sort property array or callback function

A computed property which returns a new array with all the properties from the first dependent array sorted based on a property or sort function. The sort macro can be used in two different ways:

  1. By providing a sort callback function
  2. By providing an array of keys to sort the array

In the first form, the callback method you provide should have the following signature:

1
function sortCallback(itemA, itemB);
  • itemA the first item to compare.
  • itemB the second item to compare.

This function should return negative number (e.g. -1) when itemA should come before itemB. It should return positive number (e.g. 1) when itemA should come after itemB. If the itemA and itemB are equal this function should return 0.

Therefore, if this function is comparing some numeric values, simple itemA - itemB or itemA.get( 'foo' ) - itemB.get( 'foo' ) can be used instead of series of if.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { set } from '@ember/object';
import { sort } from '@ember/object/computed';

class ToDoList {
  constructor(todos) {
    set(this, 'todos', todos);
  }

  // using a custom sort function
  @sort('todos', 'todosSortingDesc') sortedTodosDesc;
}

let todoList = new ToDoList([
  { name: 'Unit Test', priority: 2 },
  { name: 'Documentation', priority: 3 },
  { name: 'Release', priority: 1 }
]);

todoList.sortedTodos; // [{ name:'Documentation', priority:3 }, { name:'Release', priority:1 }, { name:'Unit Test', priority:2 }]
todoList.sortedTodosDesc; // [{ name:'Unit Test', priority:2 }, { name:'Release', priority:1 }, { name:'Documentation', priority:3 }]