๐ Sort Array
Question Descriptionโ
็ตฆๅฎไธๅ่ฅๅนฒๆธๅญ็้ฃๅ๏ผ่ซไฝฟ็จ sort
ๅฝๅผ๏ผๅฐ้ฃๅ้ฒ่กๆๅบ๏ผไธฆ่ซๅฐไธๅๅ
ฉ็จฎ็ๆณ๏ผ้ฝๆไพ่งฃๆณ๏ผ
- ็ฑๅฐๅฐๅคงๆๅบ(ๅๅช)
- ็ฑๅคงๅฐๅฐๆๅบ(้ๅช)
ๅๅชๆๅบโ
const numbers = [10, 5, 50, 2, 200];
// ไฝฟ็จๆฏ่ผๅฝๅผ
numbers.sort(function (a, b) {
return a - b;
});
console.log(numbers); // [2, 5, 10, 50, 200]
้ๅชๆๅบโ
const numbers = [10, 5, 50, 2, 200];
numbers.sort(function (a, b) {
return b - a;
});
console.log(numbers); // [200, 50, 10, 5, 2]
ๆ ๆๅกๅ ฅ stringโ
const mixedNumbers = [10, '5', 50, '2', 200];
mixedNumbers.sort(function (a, b) {
return Number(a) - Number(b);
});
console.log(mixedNumbers); // ['2', '5', 10, 50, 200]
ไฝ้ๅ่งฃๆณ็กๆณๆ้ค๏ผ็กๆณ่ฝๆ็บๆธๅญ็ๅญไธฒ๏ผไพๅฆ 'iphone'
, 'ipad'
็ญ็ญใ้ไบๅญไธฒๆ่ขซ่ฝๆ็บ NaN
๏ผ้็ถๅฏ่ฝๆๅบไธๆๅจๆๅพ้ข๏ผไฝไนๅฏ่ฝๅ ็บไธๅ็่ฆฝๅจ๏ผ็ข็ไธๅ็ตๆใ้็จฎ็ๆณไธ๏ผๅช่ฝ่ๆ
ฎไฝฟ็จ filter
ๅ
้ฒ่กๆ้ค้็ต้ฃๅใ
Object ๆๅบโ
const mockArray = [
{ type: 'a', label: 1 },
{ type: 'a', label: 2 },
{ type: 'c', label: 1 },
{ type: 'c', label: 3 },
{ type: 'b', label: 2 },
];