Created
July 12, 2018 18:09
-
-
Save prof3ssorSt3v3/4943c334fa84365f9aff607b9d241232 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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