2017-01-12 7 views
3

私はインタビューで私を困らせるホワイトボードタスクを持っていましたが、解決策を書いて、インタビュアーが述べていないに。二つの配列順序はarray1[0], array2[0], array1[1], array2[1]...ていると合併しなければならない(expectedResultを参照)などJavaScriptで2つの配列をマージしてその順序を保持する方法

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)

+0

'ループ' とは何を意味するのでしょうか?任意のタイプのループを使用できますか?何? – mattsven

+0

私は上記のコードに似た何かを提案したので、配列に何千もの項目が含まれていて、foreach/whileなどを避けるべきであると暗示された場合、パフォーマンスについて質問されました – azz0r

答えて

2
に変更することができ、より良い結果 を生成する長さをチェックし、その代わりに条件
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. 

であります

reduce(古典的なfor /ループ制御構造中)

const options = [[1, 12, 5], ["a", "b", "c", "d", "e"]]; 
 
const expectedResult = [1, "a", 12, "b", 5, "c", "d", "e"] 
 

 
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)

+0

ループこれ以上票を得て、それを推論する人々を知るのが大好きです。 (ループ返答の判断がなく、理解したいだけです) – azz0r

+0

ループは誤称ではありません。 –

3

それがループの内側にチェックを最小限に抑えるので、私は、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; }

2

、配列の長さをチェックします。私は、コード内で参照

問題は、だから、条件

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

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

謝辞 – azz0r

関連する問題