javascriptarraysecmascript-5

Merge two arrays in JavaScript (ES5 or below)


I have 2 arrays that I need to merge in a particular order in javascript. Here is the sample..

var alphabets = [[["a"], ["b"]], ["c"], ["d"], [["e"], ["f"]]];
var numbers   = [[["1"], ["2"]], ["3"], ["4"], [["5"], ["6"]]];

var result    = [[["a", "1"], ["b", "2"]], ["c", "3"], ["d", "4"], [["e", "5"], ["f", "6"]]];

Need help here..

here is what I have tried so far

var res = [];

var i;
for (i = 0; i < cars.length; i++) {
  res.push(alphabets[i].concat(numbers[i]));
}

Solution

  • For this quite fun "array merging" challenge... (I assume and hope this is a "minimal" example of something more complex). You definitely need a recursive function.

    A simple for loop is not enought to make sure to loop throught any deep level of the arrays without loosing yourself in a mess of duplicate code lines.


    Warning: the logic below ONLY works with two perfectly matching arrays, from the structure point of view.

    What is a recursive function by the way? : freeCodeCamp tutorial ← Best short example I know.


    So here is the CodePen demo I made for you in a couple minutes... I already knew about recursion and when to use it. But that is a wonderful example, so thanks to your question.

    const alphabets = [[["a"], ["b"]], ["c"], ["d"], [["e"], ["f"]]];
    const numbers   = [[["1"], ["2"]], ["3"], ["4"], [["5"], ["6"]]];
    
    // Expected result
    const expected  = [[["a", "1"], ["b", "2"]], ["c", "3"], ["d", "4"], [["e", "5"], ["f", "6"]]];
    
    // A merging function
    const merge = (arr1, arr2) => {
      
      return arr1.map((item, index) =>{
        
        // if the item contains arrays
        // do another recursion
        if (Array.isArray(item[0])){
          return merge(item, arr2[index])  // a recursion is a function calling itself.
        }
        
        // Otherwize, return a "merged" array
        return [item[0], arr2[index][0]]
      })
                             
    }
    
    const result = merge(alphabets, numbers)
    
    console.log("Result:\n", JSON.stringify(result))
    console.log("Expected:\n", JSON.stringify(expected))

    CodePen

    The only condition in that recursion is the string test... You may need more tests on your arrays. Be careful about any infinite loop... Causing a stack overflow!!! Have fun coding!