博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Javascript ] Array methods in depth - sort
阅读量:6375 次
发布时间:2019-06-23

本文共 1814 字,大约阅读时间需要 6 分钟。

Sort can automatically arrange items in an array. In this lesson we look at the basics including how to sort an array of strings alphabetically and the correct way to perform a numerical sort on an array of numbers. We finish as always with a practical use-case that shows not only sort in action, but also how it can be chained together with other array methods such as map and join.

 

Problem with sort number in Array:

var data = [10, 20, 15];var sorted = data.sort();console.log(sorted); // [10, 15, 20]

Code works fine, but there is a problem: 

When calling sort on an array with numbers, what actually happens is each number is converted to a string, and they're compared using their position in Unicode.

var data = [10, 20, 15, 30 ,2];var sorted = data.sort();console.log(sorted); // [10, 15, 2, 20, 30]

This is because, in Unicode, 10 does come before 2. Again, this is because these numbers are being converted to strings first.

 

To solve the problem:

var data = [10, 20, 15, 30 ,2];var sorted = data.sort( (a,b)=>{  return a-b;} );console.log(sorted);

We need to provide a comparative function to make it work. If a - b < 0 then it just put a before b;

 

Also according to that, we can compare the lenght of string, then sort them in order:

var sorted = names.sort( (a,b)=>{  return a.length - b.length;} );console.log(sorted); // ["Bob", "Kent", "Kettly", "Jusnine"]

 

A more useful example : sort objects

var list = lessons.sort( (a,b)=>{  return a.views-b.views} ).map( (lession)=>{  return `    
  • ${lession.title} - ${lession.views}
  • `;} ).join('\n');var output = `
      \n${list}\n
    `;console.log(output); /*"
    • Javascript Array methods in depth - concat - 1000
    • Javascript Array methods in depth - join - 1025
    • Javascript Array methods in depth - slice - 1050
    "*/

     

    转载地址:http://kctqa.baihongyu.com/

    你可能感兴趣的文章
    C#开发SQLServer的Geometry和Geography存储
    查看>>
    GPUImage API文档之GPUImageInput协议
    查看>>
    EBS R12.2应用层关闭脚本的执行过程
    查看>>
    js:深闭包(范围:上)
    查看>>
    使用POI导入小数变成浮点数异常
    查看>>
    Logistic Regression的几个变种
    查看>>
    PopupMenu消失(Dismiss)抓住
    查看>>
    Determining if a point lies on the interior of a polygon
    查看>>
    在 Angular 中实现搜索关键字高亮
    查看>>
    [Javascript ] Array methods in depth - sort
    查看>>
    司机福利!Uber即将可以自己选目的地接单啦!
    查看>>
    pycharm的注册(转载)
    查看>>
    MOGODB REDIS
    查看>>
    HDU 1231:最大连续子序列(DP)
    查看>>
    [java] java 中Unsafe类学习
    查看>>
    HDU 1231——最大连续子序列(DP)
    查看>>
    P1739 表达式括号匹配
    查看>>
    3.1.4 模板字符串
    查看>>
    redis 介绍和常用命令
    查看>>
    CPU的段寄存器
    查看>>