前端一些算法-es6版

js 统计一个字符串出现频率最高的字母/数字

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

let str = 'asdfghjklaqwertyuiopiaia';

const strChar = str => {

    let string = [...str],

        maxValue = '',

        obj = {},

        max = 0;

    string.forEach(value => {

        obj[value] = obj[value] == undefined ? 1 : obj[value] + 1

        if (obj[value] > max) {

            max = obj[value]

            maxValue = value

        }

    })

    return maxValue;

}

console.log(strChar(str))    // a

数组去重

1.forEach

1

2

3

4

5

6

7

8

9

let arr = ['1''2''3''1''a''b''b']

const unique = arr => {

    let obj = {}

    arr.forEach(value => {

        obj[value] = 0

    })

    return Object.keys(obj)

}

console.log(unique(arr))  // ['1','2','3','a','b']

2. filter

1

2

3

4

5

6

7

let arr = ['1''2''3''1''a''b''b']

const unique = arr => {

    return arr.filter((ele, index, array) => {

        return index === array.indexOf(ele)

    })

}

console.log(unique(arr))  // ['1','2','3','a','b']

3. set

1

2

3

4

5

let arr = ['1''2''3''1''a''b''b']

const unique = arr => {

    return [...new Set(arr)]

}

console.log(unique(arr))  // ['1','2','3','a','b']

翻转字符串

1

2

3

4

5

let str ="Hello Dog";

const reverseString = str =>{

    return [...str].reverse().join("");

}

console.log(reverseString(str))   // goD olleH

数组中最大差值

1. forEach

1

2

3

4

5

6

7

8

9

10

11

let arr = [23, 4, 5, 2, 4, 5, 6, 6, 71, -3];

    const difference = arr => {

        let min = arr[0],

            max = 0;

        arr.forEach(value => {

            if (value < min) min = value

            if (value > max) max = value

        })

        return max - min ;

    }

    console.log(difference(arr))  // 74

2. max、min

1

2

3

4

5

6

7

let arr = [23, 4, 5, 2, 4, 5, 6, 6, 71, -3];

    const difference = arr => {

        let max = Math.max(...arr),

            min = Math.min(...arr);

        return max - min ;

    }

    console.log(difference(arr)) // 74

不借助临时变量,进行两个整数的交换

1. 数组解构

1

2

3

4

let a = 2,

     b = 3;

     [b,a] = [a,b]

console.log(a,b)   // 3 2

2. 算术运算(加减)

1

2

3

4

5

6

7

8

9

10

// 输入a = 2,b = 3,输出 a = 3,b = 2

    let a = 2,

        b = 3;

    const swop = (a, b) => {

        b = b - a;

        a = a + b;

        b = a - b;

        return [a,b];

    }

    console.log(swop(2,3)) // [3,2]

3. 逻辑运算(异或)

1

2

3

4

5

6

7

8

9

let a = 2,

        b = 3;

    const swop = (a, b) => {

        a ^= b; //x先存x和y两者的信息

        b ^= a; //保持x不变,利用x异或反转y的原始值使其等于x的原始值

        a ^= b; //保持y不变,利用x异或反转y的原始值使其等于y的原始值

        return [a,b];

    }

    console.log(swop(2,3)) // [3,2]

排序 (从小到大)

1.冒泡排序

1

2

3

4

5

6

7

8

9

10

11

12

13

let arr = [43, 32, 1, 5, 9, 22];

const sort = arr => {

    let res = []

    arr.forEach((v, i) => {

        for (let j = i + 1; j < arr.length; j++) {

            if (arr[i] > arr[j]) {

                [arr[i],arr[j]] = [arr[j],arr[i]]

            }

        }

    })

    return arr

}

console.log(sort(arr))  // [1, 5, 9, 22, 32, 43]

比较两个数组的内容是否相同

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

// Warn if overriding existing method

if (Array.prototype.equals)

    console.warn(

        "Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there's a framework conflict or you've got double inclusions in your code.");

// attach the .equals method to Array's prototype to call it on any array

Array.prototype.equals = function (array) {

    // if the other array is a falsy value, return

    if (!array)

        return false;

    // compare lengths - can save a lot of time

    if (this.length != array.length)

        return false;

    for (var i = 0, l = this.length; i < l; i++) {

        // Check if we have nested arrays

        if (this[i] instanceof Array && array[i] instanceof Array) {

            // recurse into the nested arrays

            if (!this[i].equals(array[i]))

                return false;

        else if (this[i] != array[i]) {

            // Warning - two different object instances will never be equal: {x:20} != {x:20}

            return false;

        }

    }

    return true;

}

// Hide method from for-in loops

Object.defineProperty(Array.prototype, "equals", {

    enumerable: false

});

比较Object

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

Object.prototype.equals = function (object2) {

    //For the first loop, we only check for types

    for (propName in this) {

        //Check for inherited methods and properties - like .equals itself

        //Object.prototype.hasOwnProperty() - JavaScript | MDN

        //Return false if the return value is different

        if (this.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) {

            return false;

        }

        //Check instance type

        else if (typeof this[propName] != typeof object2[propName]) {

            //Different types => not equal

            return false;

        }

    }

    //Now a deeper check using other objects property names

    for (propName in object2) {

        //We must check instances anyway, there may be a property that only exists in object2

        //I wonder, if remembering the checked values from the first loop would be faster or not

        if (this.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) {

            return false;

        else if (typeof this[propName] != typeof object2[propName]) {

            return false;

        }

        //If the property is inherited, do not check any more (it must be equa if both objects inherit it)

        if (!this.hasOwnProperty(propName))

            continue;

        //Now the detail check and recursion

        //This returns the script back to the array comparing

        /**REQUIRES Array.equals**/

        if (this[propName] instanceof Array && object2[propName] instanceof Array) {

            // recurse into the nested arrays

            if (!this[propName].equals(object2[propName]))

                return false;

        else if (this[propName] instanceof Object && object2[propName] instanceof Object) {

            // recurse into another objects

            //console.log("Recursing to compare ", this[propName],"with",object2[propName], " both named \""+propName+"\"");

            if (!this[propName].equals(object2[propName]))

                return false;

        }

        //Normal value comparison for strings and numbers

        else if (this[propName] != object2[propName]) {

            return false;

        }

    }

    //If everything passed, let's say YES

    return true;

}

随机数生成

1. min ≤ r ≤ max

1

2

3

4

5

6

function RandomNumBoth(Min,Max){

      var Range = Max - Min;

      var Rand = Math.random();

      var num = Min + Math.round(Rand * Range); //四舍五入

      return num;

}

2. min ≤ r < max

1

2

3

4

5

6

function RandomNum(Min, Max) {

         var Range = Max - Min;

         var Rand = Math.random();

         var num = Min + Math.floor(Rand * Range); //舍去

         return num;

}

3. min < r ≤ max

1

2

3

4

5

6

7

8

9

function RandomNum(Min, Max) {

          var Range = Max - Min;

          var Rand = Math.random();

          if(Math.round(Rand * Range)==0){      

            return Min + 1;

          }

          var num = Min + Math.round(Rand * Range);

          return num;

    }

4. min < r < max

1

2

3

4

5

6

7

8

9

10

11

12

13

14

function RandomNum(Min, Max) {

         var Range = Max - Min;

         var Rand = Math.random();

         if(Math.round(Rand * Range)==0){

           return Min + 1;

         }else if(Math.round(Rand * Max)==Max)

         {

           index++;

           return Max - 1;

         }else{

           var num = Min + Math.round(Rand * Range) - 1;

           return num;

         }

    }

5.将数据转换成树结构

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

/**

 * 将数据转换成树结构

 * @param {array} arr - 数据

 * @param {string} idStr - id

 * @param {string} pIdStr - 父 id

 * @returns {array}

 */

function toTree(data, idStr, pIdStr) {

    if (!idStr) {

        idStr = 'id'

    }

    if (!pIdStr) {

        pIdStr = 'pId'

    }

    // 删除 所有 children ,以防止多次调用

    data.forEach(function (item) {

        delete item.children;

    });

    // 将数据存储为 以 id 为 KEY 的 map 索引数据列

    var map = {};

    data.forEach(function (item) {

        map[item[idStr]] = item;

    });

    var val = [];

    data.forEach(function (item) {

        // 以当前遍历项,的 pid,去 map 对象中找到索引的 id

        var parent = map[item[pIdStr]];

        // 如果找到索引,那么说明此项不在顶级当中,那么需要把此项添加到,他对应的父级中

        if (parent) {

            (parent.children || (parent.children = [])).push(item);

        else {

            // 如果没有在 map 中找到对应的索引 ID,那么直接把 当前的 item 添加到 val 结果集中,作为顶级

            val.push(item);

        }

    });

    return val;

}

找到某一父节点下的所有子节点

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

/**

 * 找到某一父节点下的所有子节点

 * @param {array} arr - 数据

 * @param {string|number} pid - 待查找的值

 * @param {string} idStr - id

 * @param {string} pIdStr - 父 id

 * @returns {array}

 */

function getSonsTree(arr, id, idStr, pIdStr) {

    if (!idStr) {

        idStr = 'id'

    }

    if (!pIdStr) {

        pIdStr = 'pId'

    }

    var temp = [],

        lev = 0;

    var forFn = function (arr, id, lev) {

        for (var i = 0; i < arr.length; i++) {

            var item = arr[i];

            if (item[pIdStr] == id) {

                item.lev = lev;

                temp.push(item);

                forFn(arr, item[idStr], lev + 1);

            }

        }

    };

    forFn(arr, id, lev);

    return temp;

}

找到某一父节点下的所有子节点

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

/**

 * 找到某一父节点下的所有子节点

 * @param {array} arr - 数据

 * @param {string|number} pid - 待查找的值

 * @param {string} idStr - id

 * @param {string} pIdStr - 父 id

 * @returns {array}

 */

function getSonsTree(arr, id, idStr, pIdStr) {

    if (!idStr) {

        idStr = 'id'

    }

    if (!pIdStr) {

        pIdStr = 'pId'

    }

    var temp = [],

        lev = 0;

    var forFn = function (arr, id, lev) {

        for (var i = 0; i < arr.length; i++) {

            var item = arr[i];

            if (item[pIdStr] == id) {

                item.lev = lev;

                temp.push(item);

                forFn(arr, item[idStr], lev + 1);

            }

        }

    };

    forFn(arr, id, lev);

    return temp;

}

6.输入一个值,返回其数据类型

function type(para) {

    return Object.prototype.toString.call(para)

}

console.log(type(1));

7.冒泡排序

升序 bubbleAsSort()

升序bubbleAsSort()

function bubbleAsSort(arr){

    for(let i=0; i<arr.length-1; i++){

        for (let j=0; j<arr.length-1-i; j++) {

            if (arr[j]>arr[j+1]) {

                let temp = arr[j+1];

                arr[j+1] = arr[j];

                arr[j] = temp;

            }

        }

    }

    return arr;

}

降序 bubbleDeSort()

降序 bubbleDeSort()

function bubbleDeSort(arr){

    for(let i=0;i<arr.length-1;i++){

        for(let j=0; j<arr.length-1-i;j++){

            if (arr[j]<arr[j+1]) {

                let temp = arr[j+1];

                arr[j+1] = arr[j];

                arr[j] = temp;

            }

        }

    }

    return arr;

}

8.选择排序

升序 selectAsSort()

升序 selectAsSort()

function selectAsSort(arr){

    let minIndex,temp;

    for(let i=0;i<arr.length-1;i++){

        minIndex = i;

        for(let j = i+1;j<arr.length;j++){

            if(arr[j]<arr[minIndex]){

                minIndex=j;

            }

        

        temp=arr[i];

        arr[i]=arr[minIndex];

        arr[minIndex]=temp;

    }

    return arr;

}

降序 selectDeSort()

降序 selectDeSort()

function selectDeSort(arr){

    let minIndex,temp;

    for(let i=0;i<arr.length-1;i++){

        minIndex = i;

        for(let j = i+1;j<arr.length;j++){

            if(arr[j]>arr[minIndex]){

                minIndex=j;

            }

        

        temp=arr[i];

        arr[i]=arr[minIndex];

        arr[minIndex]=temp;

    }

    return arr;

}

9.插入排序

升序 insertAsSort()

升序 insertAsSort()

function insertAsSort(arr){

    let current,preIndex;

    for(let i=1;i<arr.length;i++){

        current = arr[i];

        preIndex = i-1;

        while(preIndex>=0 && arr[preIndex]>current){

            arr[preIndex+1] = arr[preIndex];

            preIndex--;

        }

        arr[preIndex+1] = current;

    }

    return arr;

}

降序 insertDeSort()

降序 insertDeSort()

function insertDeSort(arr){

    let current,preIndex;

    for(let i=1;i<arr.length;i++){

        current = arr[i];

        preIndex = i-1;

        while(preIndex>=0 && arr[preIndex]<current){

            arr[preIndex+1] = arr[preIndex];

            preIndex--;

        }

        arr[preIndex+1] = current;

    }

    return arr;

}

10.阶乘

function factorial(num){

    let count = 1;

    for(let i=1;i<=num;i++){

        count *= i;

    }

    return count;

}

11.两个数之间累乘

function multBetride(x,y){

    let count;

    if(x<y){

        count = x;

        for(let i=x+1;i<=y;i++){

            count *= i;

        }

        return count;

    }else{

        count = y;

        for(let i=y+1;i<=x;i++){

            count *= i;

        }

        return count;

    }

}

12.累加

()里面可以放N个实参

function cumsum(){

    let sum = 0;

    for(let i=0;i<arguments.length;i++){

        sum += arguments[i];

    }

    return sum;

}

13.计时器(计算代码块(函数)执行时间)

无参 computeTime(f)

无参 computeTime(f)

function computeTime(code){

    let startTime = new Date().getTime();

    code();

    let endTime = new Date().getTime();

    let time = endTime-startTime;

    return time;

}

有参 computeTime(f)
使用方法:computeTime(f,参数1,参数2......)

有参 computeTime(f)

function computeTime(f) {

    let startTime = new Date().getTime();

    let p = [];

    for(let i=1;i<arguments.length; i++){

        p.push(arguments[i])

    }

    f.apply(null,p)

    let endTime = new Date().getTime();

    let Time = endTime - startTime;

    return Time;

}

14.数组去重

function arrDemp(arr){

    let newArr = [];

    let m = {};

    for(let i=0;i<arr.length;i++){

        let n = arr[i];

        if(m[n]){

        }else{

            newArr.push(arr[i]);

            m[n]=true;

        }

    }

    return newArr;

}

// 也可以使用ES6中的new Set,一步到位

15.统计数组中各个元素出现的次数

function staArrNum(arr){

    let obj = {};

    for(let i=0;i<arr.length;i++){

        let m = arr[i];

        if(obj.hasOwnProperty(m)){

            obj[m] += 1;

        }else{

            obj[m] = 1;

        }

    }

    return obj;

}

16.统计数组中各个元素出现的次数

staArrNum = arr => {

  let obj = {};

  for (let i = 0; i < arr.length; i++) {

    let m = arr[i];

    if (obj.hasOwnProperty(m)) {

      obj[m] += 1;

    else {

      obj[m] = 1;

    }

  }

  return obj;

}

let arr = [1, 2, 3, 6, 5, 3, 2, 1, 2, 3, 2, 1]

console.log(staArrNum(arr));  //    { '1': 3, '2': 4, '3': 3, '5': 1, '6': 1 }

17.在数组中找指定的元素,返回下标

arrFinNum = function (arr,num) {

  let index = -1;

  for (let i = 0; i < arr.length; i++) {

    if (num == arr[i]) {

      index = i;

      break;

    }

  }

  return index;

}

let arr = [1,2,3,4,5,6]

console.log(arrFinNum(arr,4));  // 3

18.删除数组中的元素

delArrNum = (arr,val) => {

  let index = arrFinNum(arr, val) //调用了前面自行添加的arrFinNum方法

  if (index != -1) {

    return arr.splice(index, 1);

  }

}

//示例

let arr = [1, 2, 3, 4, 5, 6]

arrFinNum = (arr, num) => {

  let index = -1;

  for (let i = 0; i < arr.length; i++) {

    if (num == arr[i]) {

      index = i;

      break;

    }

  }

  return index;

}

delArrNum = (arr,val) => {

  let index = arrFinNum(arr, val) //调用了前面自行添加的arrFinNum方法

  if (index != -1) {

    return arr.splice(index, 1);

  }

}

console.log(delArrNum(arr,2));  //  [ 2 ]

19.数字超过9显示省略号

num_filter = val =>{

  val = val?val-0:0;

  if (val > 9 ) {

    return "…"

  }else{

    return val;

  }

}

20.数字超过99显示99+

ninenum_filter = val =>{

  val = val?val-0:0;

  if (val > 99 ) {

    return "99+"

  }else{

    return val;

  }

}

21.获取视窗尺寸

function getViewportOffset() {

    if (window.innerWidth) {

        return {

            w: window.innerWidth,

            h: window.innerHeight

        }

    else {

        // ie8及其以下

        if (document.compatMode === "BackCompat") {

            // 怪异模式

            return {

                w: document.body.clientWidth,

                h: document.body.clientHeight

            }

        else {

            // 标准模式

            return {

                w: document.documentElement.clientWidth,

                h: document.documentElement.clientHeight

            }

        }

    }

}

22.银行卡号分割

bank_filter = val =>{

  val += '';

  val = val.replace(/(\s)/g,'').replace(/(\d{4})/g,'$1 ').replace(/\s*$/,'');

  return val;

}

23数字前补零

/**

*   num为你想要进行填充的数字

*   length为你想要的数字长度

*/

//迭代方式实现

padding1=(num, length)=> {

  for(let len = (num + "").length; len < length; len = num.length) {

      num = "0" + num;           

  }

  return num;

}

//递归方式实现

padding2=(num, length) =>{

  if((num + "").length >= length) {

      return num;

  }

  return padding2("0" + num, length)

}

//转为小数

padding3=(num, length)=> {

  let decimal = num / Math.pow(10, length);

  //toFixed指定保留几位小数

  decimal = decimal.toFixed(length) + "";

  return decimal.substr(decimal.indexOf(".")+1);

}

//填充截取法

padding4=(num, length)=> {

  //这里用slice和substr均可

  return (Array(length).join("0") + num).slice(-length);

}

//填充截取法

padding5=(num, length)=> {

  let len = (num + "").length;

  let diff = length+1 - len;

  if(diff > 0) {

      return Array(diff).join("0") + num;

  }

  return num;

}

24.对象赋值

/**

         * @desc 当两个对象有相同的key时,快速赋值

         * @param obj1 被赋值的对象

         * @param obj2 赋值的对象

         * @example

         * Tools.objToValueObj("{a:1,b:2,d:5}","{a:2,b:3,c:4}")

         * obj1: {a:2,b:3,d:5}

         */

        objToOtherObj: function (obj1, obj2) {

            Object.keys(obj1).forEach(function (key) {

                if (obj2[key]) {

                    obj1[key] = obj2[key]

                }

            })

        },

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值