手记

JS简单算法的记录

数组去重算法1:

function removeRepeat1(arr){
    var arr = [1, 1, 1, 3, 4, 4, 4, 5, 5, 5, 5, 4, 6];
     for (var i = 0; i < arr.length; i++) {
         for (var j = 0; j < arr.length; j++) {
             if (arr[i] == arr[j] && i != j) {
                //将后面重复的数删掉
                 arr.splice(j, 1);
             }
         }
     }
     alert(arr);
 }

数组去重算法2:

function removeRepeat2() {
    var arr = [1, 2, 3, 1, 55, 12, 2, 1, 3, 6];
    var result = [];
    for (var i = 0; i < arr.length; i++) {
        if (result.indexOf(arr[i]) == -1) {
            result.push(arr[i]);
        }
    }
    alert(result);
}

两个数组合并,排序:

function mergeSort() {
    var arr1 = [1, 3, 12, 67];
    var arr2 = [2, 44, 28, 16, 1];
    //数组合并
    var newArr = arr1.concat(arr2);
    //将newArr数组转换成set对象
    var arr = new Set(newArr);
    //使用Array.from()方法将set对象转换成数组,并使用sort()方法排序
    var result = Array.from(arr).sort(function(a, b){
        return a - b;
    });
    alert(result);
}

计算元素出现次数最多的元素和次数:

function checkMostElement() {
    var arr = ['1', '2', '3', '4', '5', '2', '2', '3', '4', '11', '66', '3', '2'];
    var map = {};
    for(var i = 0; i < arr.length; i++) {
        if(!map[arr[i]]) {
            map[arr[i]] = 1;
        } else {
            map[arr[i]] ++; 
        }
    }
    var element;
    var count = 0;
    for(var key in map) {
        if(map[key] > count) {
            count = map[key];
            element = key;
        }
    }
    alert("最大元素是:" + element + ",出现次数是:" + count);
}
1人推荐
随时随地看视频
慕课网APP