学习笔记--每日js练习

112 阅读1分钟

一个多维数组,去重、升序排序、扁平化输出

var arr = [    3,    [2, 6, 8, 9, 2, 5],
    [        1, 4, 2, 1, [            9, 0, 2, 3, 1, 3, 7        ]
    ],
    3,
    6
];

数组偏平化处理:多维数组转化为一维数组

方法1:map遍历,递归处理

Array.prototype.flat = function () {
    const result = this.map(item => {
        if (Array.isArray(item)) {
            return item.flat();
        }
        return [item];
    })
    return [].concat(...result);
}

方法2:while遍历,Array.some判断是否还有数组

Array.prototype.flat2 = function () {
    let result = this;
    while (result.some(item => Array.isArray(item))) {
        result = [].concat(...result);
    }
    return result;
}

数组去重

Array.prototype.unique = function () {
    return [...new Set(this)];
}

数组排序

const sortFn = (a, b) => a - b;

最后两种方法分别调用

arr.flat().unique().sort(sortFn);
arr.flat2().unique().sort(sortFn);