Arrays Sorting and Filtering

JS
S
JavaScript

Simple examples of sorting and filtering arrays

1// Sort by name
2const sortedFields = fields.sort((a: any, b: any) => { 
3    return (a.name < b.name) ? -1 : (a.name > b.name) ? 1 : 0;
4});
5
6
7// Sort by date
8events.sort((a: any, b: any) => b.createdOn - a.createdOn);
9
10
11// Other
12  sortAppointments(appointments: AppointmentModel[]): AppointmentModel[] {
13    // Sort by Slot Time
14    const slotTimeSorted = appointments.sort((a: AppointmentModel, b: AppointmentModel) => {
15      const priorityIndexA = timeSlotPriority.indexOf(a.slot.timeslot.name);
16      const priorityIndexB = timeSlotPriority.indexOf(b.slot.timeslot.name);
17      return ((priorityIndexA < priorityIndexB) ? -1 : ((priorityIndexA > priorityIndexB) ? 1 : 0));
18    });
19    // Sort by Status
20    // Sort by TimeStamp
21    console.log('sortdAppointments', slotTimeSorted);
22    return slotTimeSorted;
23  }
24
25
26const pendingResults = [
27    {doing: false},
28    {doing: true}
29];
30
31// true values first
32pendingResults.sort( (a, b) => {
33    return (a.doing === b.doing) ? 0 : a.doing ? -1 : 1
34});
35
36// false values first
37pendingResults.sort( (a, b) => {
38    return (a.doing === b.doing) ? 0 : a.doing ? 1 : -1
39});

Created on 6/7/2018