Native JavaScript Sort Method - Array.sort()

Veröffentlicht am: 22 Februar 2019
auf dem Kanal: ChirpingmermaidCodes
664
19

In this video, I'll just be going over the native Javascript sort method - Array.sort() - how to sort numbers, letters, and sort an array of objects by a specific property.
note: youtube won't allow angle brackets in the description, so i have changed the functions to ES5 to avoid using the arrow functions, and replaced the less than operator.

Numbers:
sort numbers with the following compare function passed in:
numbers.sort(function(a, b){ return a - b});

Letters:
sort words with the following compare function passed in:
words.sort(function(a, b){ return a.toLowerCase() [less than operator] b.toLowerCase() ? -1 : 1});

Array of Objects:
to sort by a specific property, just reference that property when comparing:
let people = [{name: 'Bob', age: 45}, {name: 'Alex', age: 23}, {name: 'John', age: 2}, {name: 'carrie', age: 3}];
//by name:
people.sort(function(a, b){ return a.name.toLowerCase() [less than operator] b.name.toLowerCase() ? -1 : 1});
//by age:
people.sort(function(a, b){ a.age - b.age});

Resources:
mdn: https://developer.mozilla.org/en-US/d...
repl.it: https://repl.it/@Chirpingmermaid/nati...


Auf dieser Seite können Sie das Online-Video Native JavaScript Sort Method - Array.sort() mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer ChirpingmermaidCodes 22 Februar 2019 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 664 Mal angesehen und es wurde von 19 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!