[英]How to merge two arrays in JavaScript loop
Is there a better way to do this?有一个更好的方法吗? Faster or more readable?
更快或更易读? Please share your approach.
请分享您的方法。
const a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
const b = [ 'a', 'b', 'c', 'd', 'e', 'f' ]
let i = 0
let j = 1
while (true) {
const item = b[i]
if (!item) break
a.splice(j, 0, item)
j += 2
i++
}
// expected output [0, 'a', 1, 'b', 2, 'c', 3, 'd', 4, 'e', 5, 'f', 6, 7, 8, 9]
My approach:我的做法:
function mergeBetween(a, b) {
let i = 0
let j = 1
while (true) {
const item = b[i]
if (!item) break
a.splice(j, 0, item)
j += 2
i++
}
return a
}
const a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
const b = [ 'a', 'b', 'c', 'd', 'e', 'f' ]
mergeBetween(a, b) //[0, 'a', 1, 'b', 2, 'c', 3, 'd', 4, 'e', 5, 'f', 6, 7, 8, 9]
You could iterate the array by the minimum of both array lengths and take the rest by slicing the arrays from the minimum length.您可以通过两个数组长度中的最小值来迭代数组,并通过从最小长度切片 arrays 来获取 rest。
function merge(a, b) { const result = []; l = Math.min(a.length, b.length); for (let i = 0; i < l; i++) result.push(a[i], b[i]); result.push(...a.slice(l), ...b.slice(l)); return result; } console.log(...merge([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], ['a', 'b', 'c', 'd', 'e', 'f']));
You can use either recursion:您可以使用任一递归:
const Nil =
Symbol();
const intercalate =
([x=Nil, ...xn], [y=Nil, ...yn], ret=[]) =>
x === Nil && y === Nil
? ret
: intercalate(xn, yn, ret.concat( x === Nil ? [] : x
, y === Nil ? [] : y
));
Or Array#flatMap
:或
Array#flatMap
:
const intercalate =
(xn, yn) =>
xn.flatMap((x, i) =>
i >= yn.length
? [x]
: [x, yn[i]]);
This would be my approach, if speed is your game, then you should stick to for loops... But I would suggest avoiding premature optimization in general... Not sure if that is what you meant by "faster" either...这将是我的方法,如果速度是你的游戏,那么你应该坚持 for 循环......但我建议一般避免过早优化......不确定这是否是你所说的“更快”......
const a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; const b = ["a", "b", "c", "d", "e", "f"]; // check which is longer const longer = a.length > b.length? a: b; const shorter = a.length < b.length? a: b; // declare a new variable to hold the combined array let newArray = []; for (let i = 0; i < longer.length; i++) newArray = i < shorter.length? [...newArray, longer[i], shorter[i]]: [...newArray, longer[i]]; console.log(newArray)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.