算法

数组去重

function uniq(arr) {
    return [...new Set(arr)]
}
1
2
3

取交集

let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);
let intersect = new Set([...a].filter(x => b.has(x)));
1
2
3

取多个数组的交集

var intersection = function(...args) {
    if (args.length === 0) {
    return []
  }
  if (args.length === 1) {
    return args[0]
  }
  return [...new Set(args.reduce((result, arg) => {
    return result.filter(item => arg.includes(item))
  }))]
};

1
2
3
4
5
6
7
8
9
10
11
12

取差集

let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);
let difference = new Set([...a].filter(x => !b.has(x)));
1
2
3

最快捷的数组求最大值 ?

var arr = [ 1,5,1,7,5,9];
Math.max(...arr);  // 9 

//or
Math.max.apply(Math, arr);
//or
Math.max.call(Math, ...arr);
//or
Math.max.bind(Math, ...arr)();
1
2
3
4
5
6
7
8
9

数组扁平化

reduce递归:

    function flattenDeep (arr) {
        return arr.reduce((acc, val) =>
            Array.isArray(val) 
            ? acc.concat(flattenDeep(val))
            : acc.concat(val),
        []);
    }
1
2
3
4
5
6
7

迭代:

const flatten = function (arr) {
    while (arr.some(item => Array.isArray(item))) {
        arr = [].concat(...arr)
    }
    return arr
}
1
2
3
4
5
6

toString: 只适用于简单数组

    function flatten (arr){
        return arr.toString().split(',');
        //return arr.join(',').split(',').map(item => Number(item))
    }
1
2
3
4

ES10:

    arr.flat(Infinity);
1

数字转中文

function money2Chinese(num) {
    if(typeof num !== 'number') {
        throw new Error('参数为数字')
    };

    let strOutput = "";
    let strUnit = '仟佰拾亿仟佰拾万仟佰拾元角分';
    num += "00";

    const intPos = num.indexOf('.');

    if (intPos >= 0) {
        num = num.substring(0, intPos) + num.substr(intPos + 1, 2);
    }
    strUnit = strUnit.substr(strUnit.length - num.length);

    for (let i = 0; i < num.length; i++) {
      strOutput += '零壹贰叁肆伍陆柒捌玖'.substr(num.substr(i, 1), 1) + strUnit.substr(i, 1);
    }
    
    return strOutput.replace(/零角零分$/, '整').replace(/零[仟佰拾]/g, '零').replace(/零{2,}/g, '零').replace(/零([亿|万])/g, '$1').replace(/零+元/, '元').replace(/亿零{0,3}万/, '亿').replace(/^元/, "零元");
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

驼峰写法转下划线写法

function camelCaseToUnderline (name) {
    if (typeof name !== 'string') {
        throw TypeError('传入参数不正确, 要求为字符串类型');
    }
    return name.replace(/[A-Z]/g, function (val, index) {    
    let char = val.toLowerCase();

    // 首字母为大写时无需加入下划线
    return index === 0 ? char : '_' + char;
  })
}
1
2
3
4
5
6
7
8
9
10
11

下划线写法转驼峰写法

function underlineToCamelCase (s) {
    return s.replace(/-\w/g, function(x) {
        return x.slice(1).toUpperCase();
    })
}
1
2
3
4
5
最近更新: 8/16/2020, 3:50:09 PM