Today, my former colleague told me that there was a problem called flat for me to play. I was not happy when I heard it. It is not very simple, a reduce recursion, and all you need to do is spread out the array layer by layer.

The other side said the topic to you, you try, so there is the following question.

Implement a flat method, which takes array and depth, and flatizes the array by depth. For example: - flat ([1, 2, 3, [4, 5]]) / / [1, 2, 3, 4, 5] - flat ([1, 2, 3, [[4, 5]]]] / / [1, 2, 3, 4, 5]] - flat ([1, 2, 3, [[4, 5]]]. 2) / / [1, 2, 3, 4, 5]Copy the code

Because the flat depth is not used at ordinary times, and the interview questions are rarely brushed. This was a bit of a shock, but I managed to implement the v1 version of the code:

// v1: recurse with a new function
function flat(array, depth = 1) {
    return help(array, depth, [])
}
function help(array, depth, result) {
    for (let i = 0; i < array.length; i++) {
        let item = array[i]
        if (depth > 0 && Array.isArray(item)) {
            result = result.concat(flat(item, depth - 1))}else {
            result.push(item)
        }
    }
    return result
}
Copy the code

This colleague said that many social recruitment students in the first version of the same. I thought I could use while to decide not to terminate the loop until the depth level is reached, so I changed it to v2:

// v2: while traversal, count with count, and terminate loop when count reaches depth
function flat(array, depth = 1) {
    let count = 0
    let result = array
    while (count < depth) {
        for (let i = 0; i < result.length; i++) {
            const item = result[i]
            // If it is an array, pat this item flat
            if (Array.isArray(item)) {
                result.splice(i, 1)
                result = [...result, ...item]
            }
        }
        count++
    }
    return result
}

Copy the code

The colleague continued to say, there are simpler. I think it’s still reduce, you can recursively flat yourself. Hence the V3 version:

// v3: use reduce. Each time we recurse, we decrease depth by 1. If depth is greater than 0, we flatten the item.
function flat(array, depth = 1) {
    return array.reduce((result, item) = > {
        if (depth > 0 && Array.isArray(item)) {
            result = [
                ...result,
                ...flat(item, depth - 1)]}else {
            result.push(item)
        }
        return result
    }, [[]])
}
Copy the code

Colleagues say very good very good, too excellent. I thought it had been perfect, cross-examine is not the code in your mind? They said no and gave me v4:

/ / v4: reduce
function flat(array, depth = 1) {
    return depth > 0 ? array.reduce((acc, item) = > {
        return acc.concat(Array.isArray(item) ? flat(item, depth - 1) : item)
    }, []) : array.slice()
}
Copy the code

It looks exactly the same as what I wrote about V3, but it’s different.

Well, I guess I lost it.