Typescript Object Array sorting
Demonstrate the approach of sorting object array in typescript.
var students = [
{ 'id': 1, 'name': 'Kelvin'},
{ 'id': 1, 'name': 'Marry'},
{ 'id': 1, 'name': 'John'},
]
Object array sort with comparison logic
//ascending order
sortedStudents = students.sort((first, second) => 0 - (first.id > second.id ? -1 : 1)
// descending order
sortedStudents = students.sort((first, second) => 0 - (first.id > second.id ? 1 : -1)
Use underscore lib
import * as _ from 'underscore';
_.sortBy(students, ['id']);
_.sortBy(students, ['name']);
_.sortBy(students, ['id', 'name']); //multiple fields
Use underscoroe
import * as _ from 'lodash';
_.sortBy(students, ['id']);
_.sortBy(students, ['name']);