chenshuhong / fullstack

我的全栈路线思维导图以及日常知识记录
MIT License
0 stars 0 forks source link

JavaScript数组相关 #6

Open chenshuhong opened 5 years ago

chenshuhong commented 5 years ago

去重

// 第二版
// iteratee 英文释义:迭代 重复
function unique(array, isSorted, iteratee) {
    var res = [];
    var seen = [];

    for (var i = 0, len = array.length; i < len; i++) {
        var value = array[i];
        var computed = iteratee ? iteratee(value, i, array) : value;
        if (isSorted) {
            if (!i || seen !== computed) {
                res.push(value)
            }
            seen = computed;
        }
        else if (iteratee) {
            if (seen.indexOf(computed) === -1) {
                seen.push(computed);
                res.push(value);
            }
        }
        else if (res.indexOf(value) === -1) {
            res.push(value);
        }        
    }
    return res;
}
var unique = (a) => [...new Set(a)]
chenshuhong commented 5 years ago

数组扁平化 文章链接

function flatten(arr) {

    while (arr.some(item => Array.isArray(item))) {
        arr = [].concat(...arr);
    }

    return arr;
}