JavaScript - copy each element of the first array into the second array



You are given two arrays and an index. Use the array methods slice and splice to copy each element of the first array into the second array, in order. Begin inserting elements at index n of the second array. Return the resulting array. The input arrays should remain the same after the function runs.


Solution 1 Slice & Splice



function frankenSplice(arr1, arr2, n) {
    let newArr = arr2.slice()
    for (let i = 0; i < arr1.length; i++) {
        newArr.splice(n, 0, arr1[i]);
        n++;
    }
    return newArr
}
console.log(frankenSplice([1, 2, 3], [4, 5, 6], 1));

Output:


[ 4, 1, 2, 3, 5, 6 ]

Solution 2 Spread operator



function frankenSplice(arr1, arr2, n) {
    let localArr = arr2.slice();
    localArr.splice(n, 0, ...arr1);
    return localArr;
}
console.log(frankenSplice([1, 2, 3], [4, 5, 6], 1));

Output:


[ 4, 1, 2, 3, 5, 6 ]

Solution not working or have any suggestions? Please send an email to [email protected]



Join Our Facebook Group


Share this example


Download Android App

download android app

Popular javascript Examples









codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube