数组扁平化

递归

1
2
3
4
5
6
7
8
9
10
11
function flattenArray1(array) {
let arr = [];
for (let item in array) {
if (Array.isArray(array[item])) {
arr = arr.concat(flattenArray1(array[item]));
} else {
arr.push(array[item]);
}
}
return arr;
}

转换为字符串

1
2
3
function flattenArray2(array) {
return array.toString().split(',').map(item => +item);
}

循环验证是否为数组

1
2
3
4
5
6
function flattenArray3(array) {
while (array.some(item => Array.isArray(item))) {
array = [].concat(...array);
}
return array;
}

flat(ES6)

1
2
3
function flattenArray4(array) {
return array.flat(Infinity);
}

更佳的解决方案看:
JavaScript专题之数组扁平化

数组去重

Set(ES6)

利用了Set集合中元素只会出现一次特性,将数组转换为Set集合,去重后再利用解构赋值生成新的数组,并返回。

1
2
3
function unique1(array) {
return [...new Set(array)];
}

Object 键值对

将数组中的所有元素作为对象的key和value存储在对象中,如果重复出现也不会创建新的记录。

缺陷:'8'8视为同一个值。

1
2
3
4
5
function unique2(array) {
let obj = {};
array.map(item => obj[item] = item);
return Object.values(obj);
}

map + indexOf

新建一个数组A,map遍历数组B,如果在A中没找到,则添加到A中,&&短路特性(如果前半条件不满足,后半则不执行)。

1
2
3
4
5
function unique3(array) {
let arr = [];
array.map(item => arr.indexOf(item) == -1 && arr.push(item));
return arr;
}

filter + lastIndexOf

对于每一个元素从后往前找,如果找到的下标不等于本身的下标,则说明有另一个重复元素,返回false,被filter过滤掉。

1
2
3
function unique4(array) {
return array.filter((item, index) => array.lastIndex(item) == index);
}

排序 + 正则表达式

将数组每一项转换为@结尾再拼接的字符串;对这个字符串可以使用正则表达式,把重复出现部分替换为单项;再还原为数组,去掉最后一个空数据;最后把数字转换为Number,字符串不变。||逻辑运算符在前半为true的情况下不执行后半部分,如果item是字符串,前半的结果是NaN,隐式转换为Boolean,结果是false,执行后半部分,返回字符串本身。

缺陷:'8'8视为同一个值,true最后以字符串表示。

1
2
3
4
5
function unique5(array) {
let str = array.sort().join('@') + '@';
let arr = str.replace(/(\w@)\1*/g, "$1").split('@').slice(0, -1);
return arr.map(item => item - 0 || item);
}

更佳的解决方案看:
JavaScript专题之数组去重

树转换

let root = [{
    id: '1'
}, {
    id: '2',
    child: [{
            id: '2-1'
        },
        {
            id: '2-2'
        }
    ]
}, {
    id: '3',
    child: [{
        id: '3-1',
        child: [{
            id: '3-1-1'
        }, {
            id: '3-1-2'
        }]
    }]
}];
function foo(root) {
    let arr = [];
    const fn = function (root, obj) {
        for (let key in root) {
            let item = root[key];
            if (item.child) {
                fn(item.child, {
                    id: item.id,
                    father: obj
                });
            } else {
                arr.push({
                    id: item.id,
                    father: obj
                });
            }
        }
    }
    fn(root, null);
    return arr;
}
console.log(foo(root));