JavaScript - 合并两个不同大小的数组

JavaScript - Merge two arrays with different sizes

我有两个数组:

var array1= [1,3,5,7,9,11]
var array2= [undefined,4,6]

我需要合并 array1 的一个元素,然后是 array2 的一个元素,等等。这是我的代码:

function mergeArrays(array1, array2){
    var array3 = []; 
    maxlength = Math.max(array1.length, array2.length);

for(i=0;i<maxlength;i++){   
    array3.push(array1[i]);  
    array3.push(array2[i]);
}      
    return console.log(array3);
}

现在的输出是:

array3 = [1,undefined,3,4,6,7,undefined,9,undefined,11,undefined]

我需要输出为:

array3 = [1,undefined,3,4,6,7,8,11]

我的意思是,我不能使用 (!= undefined),因为如果我在数组中间有一个 undefined,它就必须在那里。

您没有检查较短数组的长度。 您的函数正在获取一个高于数组长度的值,因此额外未定义。这应该可以完成工作

var array1 = [1, 3, 5, 7, 9, 11];
var array2 = [undefined, 4, 6];

function mergeArrays(array1, array2) {
  var array3 = [];
  maxlength = Math.max(array1.length, array2.length);

  for (i = 0; i < maxlength; i++) {
    if (i < array1.length) array3.push(array1[i]);
    if (i < array2.length) array3.push(array2[i]);
  }
  return console.log(array3);
}

mergeArrays(array1, array2);

您可以检查数组长度,而不是检查 undefined,如下所示:

const array1 = [1,3,5,7,9,11]
const array2 = [undefined,4,6]

function mergeArrays(array1, array2){
    const array3 = []; 
    const maxlength = Math.max(array1.length, array2.length);

    for(let i = 0; i < maxlength; i++) {
        if (i < array1.length) {
            array3.push(array1[i]);  
        }
        
        if (i < array2.length) {
            array3.push(array2[i]);
        }
    }
    
    return array3;
}

console.log(mergeArrays(array1, array2));

您可以获取两个数组的最大长度并循环直到达到该值。循环时,检查是否超出长度并推入结果。

const allEqual = (...args) =>
  ((head, ...tail) => tail.every(curr => curr === head))
  (args.map(v => JSON.stringify(v)));

const test = ({ actual, expected }) => {
  console.log(JSON.stringify(actual));
  console.log(allEqual(actual, expected));
};

const interlaceArrays = (...arrays) => {
  const result = [];
  const maxLen = Math.max(...arrays.map(({ length }) => length));
  for (let i = 0; i < maxLen; i++) {
    arrays.forEach(arr => {
      if (i < arr.length) result.push(arr[i]);
    })
  }
  return result;
};

const
  odd = [1, 3, 5, 7, 9, 11],
  even = [undefined, 4, 6],
  other = ['a', 'b'];

test({
  actual: interlaceArrays(odd, even),
  expected: [1, undefined, 3, 4, 5, 6, 7, 9, 11]
});

test({
  actual: interlaceArrays(odd, even, other),
  expected: [1, undefined, 'a', 3, 4, 'b', 5, 6, 7, 9, 11]
});
.as-console-wrapper { top: 0; max-height: 100% !important; }