Learn JavaScript SORTING in 6 minutes! 🗃

preview_player
Показать описание
// sort() = method used to sort elements of an array in place.
// Sorts elements as strings in lexicographic order, not alphabetical
// lexicographic = (alphabet + numbers + symbols) as strings
Рекомендации по теме
Комментарии
Автор

// sort() = method used to sort elements of an array in place.
// Sorts elements as strings in lexicographic order, not alphabetical
// lexicographic = (alphabet + numbers + symbols) as strings

// EXAMPLE 1
const numbers = [1, 10, 2, 9, 3, 8, 4, 7, 5, 6];

numbers.sort((a, b) => a - b); //FORWARD
numbers.sort((a, b) => b - a); //REVERSE

console.log(numbers);

// EXAMPLE 2
const people = [{name: "Spongebob", age: 30, gpa: 3.0},
{name: "Patrick", age: 37, gpa: 1.5},
{name: "Squidward", age: 51, gpa: 2.5},
{name: "Sandy", age: 27, gpa: 4.0}]

people.sort((a, b) => a.age - b.age); //FORWARD
people.sort((a, b) => b.age - a.age); //REVERSE

people.sort((a, b) => a.gpa - b.gpa); //FORWARD
people.sort((a, b) => b.gpa - a.gpa); //REVERSE

people.sort((a, b) => //FORWARD
people.sort((a, b) => //REVERSE

console.log(people);

BroCodez
Автор

Thank you dude.
Lol You did squidward dirty giving him a gpa lower than spongebob

alexkiiru
Автор

Thanks brother this video is very easy to understand

code-with-jimy
Автор

1:40 - Thanks for explaining the a - b thing in sort(). I didn't understand what was going on under the hood.

JamieDawsonCodes
Автор

Thank you, you made this easy to understand

latostadaa
Автор

Thank You! you make it easy to understand.

JadeWays
Автор

i want re-sort object according to name preserving keys
//js
const people = {1:{name:'carole', age:13}, 2:{name:'bob', age:12}, 3:{name:'alice', age:11}}
//required output
people = {3:{name:'alice', age:11}, 2:{name:'bob', age:12}, 1:{name:'carole', age:13}}

khansikki
Автор

Why sort method works for only numbers below 10 ? Like wise in example apart from using Arrow function

LearnwithRandomYoutuber
Автор

this helped in understanding how sort() works but i need to sort the outputs of mathemetical functions, how do you do that?

malablondi
Автор

Hey Bro!
Thank you!
Can I keep the original order?
And sort into another array?

janosjanosi
Автор

hey Bro thanks for your videos, can you make some projects to understand how to use all this JavaScript methods for a website ?

vallunacoder.wecodetogether
Автор

What’s the complexity of this sort() method

tanviranjum
Автор

so the parameter a is the the first and the parameter b is the second..

can we switch the two parameter so that b is the first and a is the second? just like this? in the number.sort((b, a) => b - a)

shieldanime
Автор

i would think squidward is more intelligent than spongebob

allhailalona