簡體   English   中英

如何在 JavaScript 中合並兩個數組並保持它們的順序

[英]How to merge two arrays in JavaScript and keep their order

我有一個白板任務讓我在面試中難住了,但是我已經寫了一個解決方案,並想知道是否有人在我迭代時對其進行了改進,而面試官說不要。 這兩個數組必須以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)

我采用經典的方式,使用 while 循環,因為它最大限度地減少了循環內部的檢查,並在沒有其他檢查的情況下只附加了一個數組的其余部分。

 function mergeArrays(first, second) { var min = Math.min(first.length, second.length), i = 0, result = []; while (i < min) { result.push(first[i], second[i]); ++i; } return result.concat(first.slice(min), second.slice(min)); } const options = [[1, 12, 5], ["a", "b", "c", "d", "e"]]; console.log(mergeArrays(...options));
 .as-console-wrapper { max-height: 100% !important; top: 0; }

使用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)

在每一步,使用concat將兩個元素添加到累加器數組a中。

不要在 if conditions 中使用 value,而是檢查數組的長度。

我在代碼中看到的問題是條件

   if (second[key]) returnArray.push(second[key])
   // will not run if second[key] is 0,null,undefined.
   if (!first[key + 1] && second[key + 1]) 
   // will produce unwanted result if value reference is 0,null,undefined.

所以相反,檢查長度會產生更好的結果 所以條件

    if (second[key]) returnArray.push(second[key]) 

可以改成

   if( second.length > key) returnArray.push(second[key]) 

您可以使用遞歸壓縮函數,使用 spread 將兩個數組作為其參數提供給它:

 var z = (a, b) => a.length ? [a[0], ...z(b, a.slice(1))] : b; var options = [ [1, 12, 5], ["a", "b", "c", "d", "e"] ]; var expectedResult = z(...options); console.log(JSON.stringify(expectedResult));

或者對於任意數量的數組輸入:

 var z = (a = [], ...b) => b.length ? a.length ? [a[0], ...z(...b, a.slice(1))] : z(...b) : a; var options = [ [1, 2], '♦♡♣♤♥♢', ['A', 'B', 'C'], ['😊', '😔', '😠'], [null, NaN, undefined] ]; var expectedResult = z(...options); var stringify = (o) => JSON.stringify(o, (k, v) => v === undefined ? '__undefined__' : v !== v ? '__NaN__' : v).replace(/"__undefined__"/g, 'undefined').replace(/"__NaN__"/g, 'NaN'); console.log(stringify(expectedResult));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM