简体   繁体   中英

Insert elements from one array to another after each 'n' index

Native JS. Have 2 arrays, for example

arr1 = ['orange', 'blue', 'red', 'black', 'white', 'magenta', 'cyan']
arr2 = [1, 2, 3]

I need a function, that combine this 2 arrays, like this

function arrInsertAfter(arr1, arr2, afterElement) 
// for example make afterElement = 2 - insert element of second array after each 2 elements of first array

....

And result should be

['orange', 'blue', 1, 'red', 'black', 2, 'white', 'magenta', 3, 'cyan']

If afterElement = 3 for example it should return

['orange', 'blue', 'red', 1, 'black', 'white', 'magenta', 2, 'cyan', 3] // append remaining elements of second array at the end simply

It's important to not use any third-party connected lib's.

Here is my function

let arr1 = ['orange', 'blue', 'red', 'black', 'white', 'magenta', 'cyan'],
        arr2 = [1, 2, 3];

function arrInsertAfter(arr1, arr2, afterElement) {

        let curPos = afterElement;

        arr2.forEach(function(e) {
            arr1.splice(curPos, 0, e);
            curPos = afterElement+curPos+1;
        });

        return arr1;

    }

With traditional loop

  function arrInsertAfter(arr1, arr2, afterElement) {

    let curPos = afterElement;

      for (let i = 0; i < arr2.length; i++) {
        arr1.splice(curPos, 0, arr2[i]);
        curPos = (curPos+afterElement)+1;
      }     

      return true;
    }

    arrInsertAfter(arr1, arr2, 2);

    alert(arr1);

This should do :)

 function arrInsertAfter(arr1, arr2, afterElement){ result = []; for(var i = 1; arr2.length>0 || arr1.length>0;i++){ if(arr1.length>0){ result.push(arr1.shift()); } if(i%afterElement==0 && arr2.length>0){ result.push(arr2.shift()); } } return result; } const arr1 = ['orange', 'blue', 'red', 'black', 'white', 'magenta', 'cyan']; const arr2 = [1, 2, 3]; result = arrInsertAfter(arr1, arr2, 3); console.log(result); 

Using forEach on an array you are mutating in the callback function can be tricky to do. Here's a mutating approach using traditional loops and splice to add elements into the a array at specific index locations:

 function arrInsertAfter(a, b, after) { let j = 0; for (let i = after; i < a.length && j < b.length; i += after) { a.splice(i++, 0, b[j++]); } while (j < b.length) { a.push(b[j++]); } } const arr1 = ['orange', 'blue', 'red', 'black', 'white', 'magenta', 'cyan']; const arr2 = [1, 2, 3]; arrInsertAfter(arr1, arr2, 3); console.log(arr1); 

Here's a non-mutating version that preserves both parameters:

 function arrInsertAfter(a, b, after) { const res = a.slice(0); let j = 0; for (let i = after; i < res.length && j < b.length; i += after) { res.splice(i++, 0, b[j++]); } while (j < b.length) { res.push(b[j++]); } return res; } const arr1 = ['orange', 'blue', 'red', 'black', 'white', 'magenta', 'cyan']; const arr2 = [1, 2, 3]; console.log(arrInsertAfter(arr1, arr2, 2)); console.log(arrInsertAfter(arr1, arr2, 3)); 

And if you don't mind mutating b :

 const arrInsertAfter = (a, b, after) => a.reduce((r, e, i) => r.concat(i && i % after === 0 && b.length ? [b.shift(), e] : [e]) , []).concat(b) ; const arr1 = ['orange', 'blue', 'red', 'black', 'white', 'magenta', 'cyan']; const arr2 = [1, 2, 3]; console.log(arrInsertAfter(arr1, arr2.slice(), 2)); console.log(arrInsertAfter(arr1, arr2, 3)); 

You could take a copy and splice the elements at the right position.

 function insertAfter(array1, array2, n) { var temp = array1.slice(); array2.forEach((v, i) => temp.splice((i + 1) * n + i, 0, v)); return temp; } console.log(insertAfter(['orange', 'blue', 'red', 'black', 'white', 'magenta', 'cyan'], [1, 2, 3], 2)); console.log(insertAfter(['orange', 'blue', 'red', 'black', 'white', 'magenta', 'cyan'], [1, 2, 3], 3)); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM