js数组扁平化,去重,排序

const arr = [1, 2, 4, [3, 34, 52, 9, [0, 1, 92]], [19, 22, 3]]
// 拍平
function flat(arr) {
    const isDeep = arr.some(item => item instanceof Array)
    if (!isDeep) {
        return arr
    }
    const res = Array.prototype.concat.apply([], arr)
    return flat(res)
}
// 去重
function unique(arr) {
    const res = new Set(arr)
    return [...res]
}
// 排序
function sort(arr) {
    const compare = (a, b) => {
        if (a < b) return -1
        if (a > b) return 1
        if (a === b) return 0
    }
    return arr.sort(compare)
}
const res = sort(unique(flat(arr)))
console.log(res) // [0, 1, 2, 3, 4, 9, 19, 22, 34, 52, 92]

你可能感兴趣的:(javascript)