zoukankan      html  css  js  c++  java
  • js 自带的 sort() 方法

    1. 方法概述

       Arraysort()方法默认把所有元素先转换为String再根据Unicode排序,

       sort()会改变原数组,并返回改变(排序)后的数组 。

    2. 例子

      2.1  如果没有提供自定义的方法, 数组元素会被转换成字符串,并返回字符串在Unicode编码下的顺序比较结果

    var fruit = ['cherries', 'apples', 'bananas'];
    fruit.sort(); // ['apples', 'bananas', 'cherries']
    
    var scores = [1, 10, 2, 21]; 
    scores.sort(); // [1, 10, 2, 21]
    // Watch out that 10 comes before 2,
    // because '10' comes before '2' in Unicode code point order.
    
    var things = ['word', 'Word', '1 Word', '2 Words'];
    things.sort(); // ['1 Word', '2 Words', 'Word', 'word']
    // In Unicode, numbers come before upper case letters,
    // which come before lower case letters.

    2.2 利用map来排序

    // the array to be sorted
    var list = ['Delta', 'alpha', 'CHARLIE', 'bravo'];
    
    // temporary array holds objects with position and sort-value
    var mapped = list.map(function(el, i) {
      return { index: i, value: el.toLowerCase() };
    })
    
    // sorting the mapped array containing the reduced values
    mapped.sort(function(a, b) {
      return +(a.value > b.value) || +(a.value === b.value) - 1;
    });
    
    // container for the resulting order
    var result = mapped.map(function(el){
      return list[el.index];
    });
    
    alert(result);

    参考 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

       

  • 相关阅读:
    力扣第945题 使数组唯一的最小增量
    力扣第365题 水壶问题
    力扣面试题40 最小的k个数
    力扣第409题 最长回文串
    力扣第46题 全排列
    力扣第1160题 拼写单词
    力扣面试题01.06 字符串压缩
    力扣第695题 岛屿的最大面积
    树莓派 鼠标自动消失
    树莓派 VNC 远程桌面 同一个桌面
  • 原文地址:https://www.cnblogs.com/rocky-fang/p/5757772.html
Copyright © 2011-2022 走看看