[英]Merge Two arrays of different lengths alternatively, JavaScript
我想交替加入兩個不同長度的數組。
const array1 = ['a', 'b', 'c', 'd'];
const array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const result = array1.reduce((arr, v, i) => arr.concat(v, array2[i]), []);
當運行此代碼時,結果為['a', 1, 'b', 2, 'c', 3, 'd', 4]
我想要['a', 1, 'b', 2, 'c', 3, 'd', 4,5,6,7,8,9]
const array1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const array2 = [1, 2, 3, 4];
const result = array1.reduce((arr, v, i) => arr.concat(v, array2[i]), []);
運行此代碼時的結果因此, ['a', 1, 'b', 2, 'c', 3, 'd', 4,'e',undefined,'f',undefined,'g',undefined]
我想要['a', 1, 'b', 2, 'c', 3, 'd', 4,'e','f','g']
有兩種情況。
如果數組1較短,則數組2中的某些值將丟失。
如果數組1長,則在合並的數組之間插入undefined。
如何不考慮長度如何交替合並兩個數組?
當我使用Swift
,使用zip2sequence
是一個簡單的解決方案。 JavaScript
有類似的東西嗎?
使用for
循環而不是reduce
,因此您不會受到任何一個數組長度的限制。
const array1 = ['a', 'b', 'c', 'd']; const array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const len = Math.max(array1.length, array2.length); const result = []; for (let i = 0; i < len; i++) { if (array1[i] !== undefined) { result.push(array1[i]); } if (array2[i] !== undefined) { result.push(array2[i]); } } console.log(result);
您也可以使用Array.reduce解決這個問題,方法是先確定哪個數組是較長的數組:
const array1 = ['a', 'b', 'c', 'd']; const array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]; let merge = (a,b) => { let short, long a.length > b.length ? (long=a, short=b) : (long=b, short=a) return long.reduce((r,c,i) => { short[i] ? r.push(short[i]) : 0 return r.push(c) && r }, []) } console.log(merge(array1,array2)) console.log(merge(array2,array1))
僅使用一個Array.forEach的解決方案要簡單一些:
const array1 = ['a', 'b', 'c', 'd']; const array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]; let merge = (a,b) => { let short, long, r=[] a.length > b.length ? (long=a, short=b) : (long=b, short=a) long.forEach((x,i) => short[i] ? r.push(short[i], x) : r.push(x)) return r } console.log(merge(array1,array2)) console.log(merge(array2,array1))
如果要使用lodash
,則將類似於:
const array1 = ['a', 'b', 'c', 'd']; const array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]; let merge = (a,b) => _.compact(_.flatten(_.zip(a,b))) console.log(merge(array1,array2)) console.log(merge(array2,array1))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
const interleave = ([x, ...xs], ys) => x ? [x, ...interleave(ys, xs)] : ys const array1 = ['a', 'b', 'c', 'd']; const array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]; console.log(interleave(array1, array2)) console.log(interleave(array2, array1))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.