zoukankan      html  css  js  c++  java
  • 数组排序去重

    1.数组排序

      升序

            var arr = [1,4,24,21,44,22,24,41,5,7,56,7];
            console.log(arr);//[1, 4, 24, 21, 44, 22, 24, 41, 5, 7, 56, 7]
            var arr2 = [];
            arr.sort(function(x,y){
                return x-y;//升序
            })
            console.log(arr); // [1, 4, 5, 7, 7, 21, 22, 24, 24, 41, 44, 56]

      降序

           arr.sort(function(x,y){
                return y-x;//降序
            })
            console.log(arr);//[56, 44, 41, 24, 24, 22, 21, 7, 7, 5, 4, 1]

    2.数组去重(不排序的)

            var arr = [1,4,24,21,44,22,24,41,5,7,56,7];
            console.log(arr);//[1, 4, 24, 21, 44, 22, 24, 41, 5, 7, 56, 7]
            var arr2 = [];
            for(var i = 0;i<arr.length;i++){
                if (arr2.indexOf(arr[i]) == '-1') {
                    arr2.push(arr[i]);
                }
            }
            console.log(arr2);//  [1, 4, 24, 21, 44, 22, 41, 5, 7, 56]

      排序去重(根据具体是升序还是降序排序)

      

            var arr = [1,4,24,21,44,22,24,41,5,7,56,7];
            console.log(arr);//[1, 4, 24, 21, 44, 22, 24, 41, 5, 7, 56, 7]
            var arr2 = [];
            arr.sort(function(x,y){
                return x-y;//升序
            })
            console.log(arr); // [1, 4, 5, 7, 7, 21, 22, 24, 24, 41, 44, 56]
            for(var i = 0;i<arr.length;i++){
                if (arr2.indexOf(arr[i]) == '-1') {
                    arr2.push(arr[i]);
                }
            }
            console.log(arr2);//  [1, 4, 5, 7, 21, 22, 24, 41, 44, 56]
  • 相关阅读:
    Matlab编辑器背景修改
    Booksim的运行
    illustrator画梯形
    latex去掉页眉
    latex字体颜色
    latex字体
    Methods to reduce the number of pipeline stages
    Basic Router Architecture
    Linux /sbin/service脚本一个基本无影响的bug
    HTML5实战之桌面通知
  • 原文地址:https://www.cnblogs.com/SunShineM/p/7680906.html
Copyright © 2011-2022 走看看