Coding - 碼農筆記 / JavaScript

JavaScript – sort的運用

Array.prototype.sort()

sort() 方法將陣列中的元素排列至其應當的位置上並返回此陣列。預設的排列順序根據Unicode字串碼位來排序。

 

字串排序

var names = ["Jj","May","Ken"];
console.log(names.sort());

// ["Jj", "Ken", "May"]

 

數字排序

var numbers = [101,20,99];
// 小到大
console.log(numbers.sort((a, b) => a - b));
// [20, 99, 101]


// 大到小
console.log(numbers.sort((a,b) => b - a));
// [101, 99, 20]

 

結合join,map運用

重新排序 lessons 裡 views由多到少的課程,並組成ul及li輸出

var lessons = [
  {
    title: 'JavaScript Array methods in depth - concat',
    views: 1000
  },
  {
    title: 'JavaScript Array methods in depth - slice',
    views: 1050
  },
  {
    title: 'JavaScript Array methods in depth - join',
    views: 1025
  }
];

var list = lessons
  .sort((a,b) => b.views - a.views)
  .map(x => `    <li>${x.title} (${x.views})</li>`)
  .join('\n'); // 每個li加上\n 換行

var output = `<ul>\n ${list} \n</ul>`;

console.log(output);


輸出結果:
"<ul>
<li>JavaScript Array methods in depth - slice (1050)</li>
<li>JavaScript Array methods in depth - join (1025)</li>
<li>JavaScript Array methods in depth - concat (1000)</li> 
</ul>"

 

MDN範例解說

© 2024 胡同筆記 | WordPress Theme: Cosimo by CrestaProject.