Interleave arrays?

Interleave arrays?
0

#1

Hey guys, I’m trying to solve it and know I’m not quite there yet, but looking for some guidance…

Write function named interleave that will take two arrays and interleaves them

Example:

if you pass it ["a", "b", "c"] and ["d", "e", "f"] then it should return ["a", "d", "b", "e", "c", "f"]
NOTE: you can assume each input will be the same length

My code:

function interleave (arr, arr2) {
    let newArr = [];
    for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr2.length; j++) {
            newArr.push(arr[i], arr2[j]);
        }
    }
    
    
    
    return newArr;
};

#2

here’s a hint. You only need one for loop to solve this…


#3

Yeah, just have this now…it might be it…

function interleave (arr, arr2) {
    let newArr = [];
    for (let i = 0; i < arr.length; i++) {
        newArr.push(arr[i], arr2[i]);
    }
    
    return newArr;
};

#4

Glad you got it figured out. How about an solution using reduce?

const interleave = (arr, arr2) => arr
  .reduce((combArr, elem, i) => combArr.concat(elem, arr2[i]), []); 

#5

Oh god, I’m gonna have to look up exactly what is going on here! :persevere: