Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Created July 12, 2018 18:09
Show Gist options
  • Save prof3ssorSt3v3/4943c334fa84365f9aff607b9d241232 to your computer and use it in GitHub Desktop.
Save prof3ssorSt3v3/4943c334fa84365f9aff607b9d241232 to your computer and use it in GitHub Desktop.
//Array custom sort() function
let log = console.log;
let movies = ['Star Wars', 'Star Trek', 'Jaws', 'Jurassic Park', 'Gross Pointe Blank', 'Eternal Sunshine of the Spotless Mind', 'Memento', 'Dog Soldiers', 'The Host', 'Gran Torino', 'Close Encounters of the Third Kind', 'Good Will Hunting', 'Layer Cake', 'Casino Royale', 'Almost Famous'];
let numbers = [40,16,67,345,22,23,142,63,59,283];
let people = [
{"id":123, "name":"Rick Deckard", "email":"rick@bladerunner.org"},
{"id":456, "name":"Roy Batty", "email":"roy@replicant.io"},
{"id":789, "name":"J.F. Sebastian", "email":"j.f@tyler.com"},
{"id":258, "name":"Pris", "email":"pris@replicant.io"}
];
//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 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment