-
-
Save martinandersen3d/38c3f5c467a20e1e62bdd257c43d29b0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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":"[email protected]"}, | |
{"id":456, "name":"Roy Batty", "email":"[email protected]"}, | |
{"id":789, "name":"J.F. Sebastian", "email":"[email protected]"}, | |
{"id":258, "name":"Pris", "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 ); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment