array custom sort() function
need to do a deeper dive
by Ken Sprague
JavaScript
//array custom sort() function
let log = console.log;
let movies = ['Batman Dark Knight', 'Avengers', 'Iron Man', 'Spiderman', 'Superman', 'Swamp Thing', 'Ghost Rider', 'Daredevil', 'Ghost in a Shell', 'Akira', 'Gaurdians of the Galaxy', 'Aquaman', 'Wonder Woman', 'Deapool', 'Xmen'];
let numbers = [42, 16, 3, 65, 324, 25, 27, 143, 68, 53, 282];
let people = [
{'id':123, 'name':'Bruce Wayne', 'email':'[email protected]'},
{'id':456, 'name':'Clark Kent', 'email':'[email protected]'},
{'id':789, 'name':'Barry Allen', 'email':'[email protected]'},
{'id':135, 'name':'Joker', 'email':'[email protected]'}
];
//the problem with numbers
log( movies.sort() ); //ok
log( numbers.sort() ); //NOT ok
//the solution - using a custom sort
let sortedNum = numbers.sort( (a, b)=>{
log('sorting', a, b);
if ( a > b ) return 1;
else if ( b > a ) return -1;
else return 0;
} );
log(sortedNum);
//sorting array of objects - using a custom sort
//sort by person name
let sortedPeople = people.sort( (a, b ) => {
if ( a.id > b.id ) return 1;
else if ( b.id > a.id ) return -1;
else return 0;
} );
log( sortedPeople );