I am using Angular2, I would like to sort array of objects based on properties in the object. I need to paginate those objects because of limitation of space. So, I do not want to use Pipe in the context of NgFor. I just would like to implement a sorting function before it rendered into DOM. If someone has some information, could you give some guide? All I found was using PipeTransform. So, I am asking you.
2 Answers
try array.sort() of JS
Example arr.sort()
var fruit = ['cherries', 'apples', 'bananas'];
fruit.sort(); // ['apples', 'bananas', 'cherries']
Example arr.sort(compareFunction)
var items = [
{ name: 'Edward', value: 21 },
{ name: 'Sharpe', value: 37 },
{ name: 'And', value: 45 },
{ name: 'The', value: -12 },
{ name: 'Magnetic', value: 13 },
{ name: 'Zeros', value: 37 }
];
// sort by value
items.sort(function (a, b) {
return a.value - b.value;
});
// sort by name
items.sort(function(a, b) {
var nameA = a.name.toUpperCase(); // ignore upper and lowercase
var nameB = b.name.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});