[英]How to merge two arrays in JavaScript loop
有一個更好的方法嗎? 更快或更易讀? 請分享您的方法。
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]
我的做法:
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]
您可以通過兩個數組長度中的最小值來迭代數組,並通過從最小長度切片 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']));
您可以使用任一遞歸:
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
));
或Array#flatMap
:
const intercalate =
(xn, yn) =>
xn.flatMap((x, i) =>
i >= yn.length
? [x]
: [x, yn[i]]);
這將是我的方法,如果速度是你的游戲,那么你應該堅持 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.