let fruits = ["Grape", "Banana", "Apple"];
fruits.sort();
console.log(fruits); // [ 'Apple', 'Banana', 'Grape' ]
let nums = [1, 2, 3, 99, 18, 26, 17];
nums.sort();
console.log(nums); // [ 1, 17, 18, 2, 26, 3, 99 ]
由於這樣的排列方式很不自然,number類型資料也不能照順序排好,事實上sort()還是可以照大小順序來排number type資料的,只是比較不直觀,跟 map() 、 filter() 等方法一樣需要用到 callback function。
//由小到大
nums.sort((a, b) => a - b);
console.log(nums); // [ 1, 2, 3, 17, 18, 26, 99 ]
//由大到小
nums.sort((a, b) => b - a);
console.log(nums); // [ 99, 26, 18, 17, 3, 2, 1 ]
另外,也可以根據字串長度對string類型資料排序,原理與上例類似:
// 根據字串長度排列
let wizzards = ["Harry", "Ron", "Hermione"]
wizzards.sort((a, b) => {
return a.length - b.length;
})
console.log(wizzards); // [ 'Ron', 'Harry', 'Hermione' ]