[["a", "b"], ["n", "m"], ["0", "1"]] => ["am0", "am1", "an0", "an1", "bm0", ...]

508 阅读1分钟

1. 问题

[["a", "b"], ["n", "m"], ["0", "1"]] 转为 ["am0", "am1", "an0", "an1", "bm0", "bm1", "bn0", "bn1"]

2. 解法

function changeArr (arr) {
    const newArr = [...arr]
    let result = newArr.shift()
    while (newArr.length) {
        const other = newArr.shift()
        const newResult = []
        result.forEach(item => {
            other.forEach(_item => {
                newResult.push(item + '' + _item)
            })
        })
        result = [...newResult]
    }
    return result
}
const arr = [['a', 'b'], ['m', 'n'], [0, 1]]
const result = changeArr(arr)
console.log(result) // ["am0", "am1", "an0", "an1", "bm0", "bm1", "bn0", "bn1"]

const arr2 = [['a', 'b'], ['m', 'n', '0'], [0, 1], ['#', '$']]
const result2 = changeArr(arr2)
console.log(result2) 
// (24) ["am0#", "am0$", "am1#", "am1$", "an0#", "an0$", "an1#", "an1$", "a00#", "a00$", "a01#", "a01$", "bm0#", "bm0$", "bm1#", "bm1$", "bn0#", "bn0$", "bn1#", "bn1$", "b00#", "b00$", "b01#", "b01$"]

3. 解析

function changeArr (arr) {
    // 赋值:赋值给一个新的对象,这样修改之后不会影响之前的值
    const newArr = [...arr]
    // 取值:获取数组的第一个值
    let result = newArr.shift()
    // 循环这个数组
    while (newArr.length) {
        // 取值:从这个数组中再次获取第一个值
        const other = newArr.shift()
        // 定义一个新的数组为 []
        const newResult = []
        // 循环 result 
        result.forEach(item => {
            // 循环 other
            other.forEach(_item => {
                // 把数据组合返回给定义的数组
                newResult.push(item + '' + _item)
            })
        })
        // 把 result 赋值给 newResult
        result = [...newResult]
    }
    return result
}

4. 总结

一个类似于广度优先遍历的方式来实现,这样时间复杂度好像也不小...暂时想不到更好的方法。