如何在 JavaScript 中合并两个数组并保持它们的顺序

azz*_*z0r 5 javascript arrays multidimensional-array

我有一个白板任务让我在面试中难住了,但是我已经写了一个解决方案并想知道是否有人在我迭代时对其进行了改进,而面试官说不要。这两个数组必须以array1[0], array2[0], array1[1], array2[1]...(见expectedResult)等的顺序合并

const options = [[1, 12, 5], ["a", "b", "c", "d", "e"]]
const expectedResult = [1, "a", 12, "b", 5, "c", "d", "e"]

function mergeArrays(first, second) {
  let returnArray = []
  
  first.forEach((value, key) => {
    returnArray.push(value)
    if (second[key]) returnArray.push(second[key])
    if (!first[key + 1] && second[key + 1]) {
      returnArray.push(
        ...second.slice(key + 1, second.length)
      )
    }
  })
  return returnArray
}

const result = mergeArrays(options[0], options[1])
console.log(result.toString() === expectedResult.toString(), result)
Run Code Online (Sandbox Code Playgroud)

use*_*737 3

With reduce(作为经典 for/while 循环控制结构的替代)

const options = [[1, 12, 5], ["a", "b", "c", "d", "e"]];
const expectedResult = [1, "a", 12, "b", 5, "c", "d", "e"]

// a is the accumulator
// cV, cI are resp. current value and current index
result = options[0].reduce(function (a, cV, cI) {
    return a.concat([cV,options[1][cI]]);
},[]);


result = result.concat(options[1].splice(options[0].length));
console.log(result.toString() === expectedResult.toString(), result)
Run Code Online (Sandbox Code Playgroud)

a在每个步骤中,使用向累加器数组添加两个元素concat