Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert two consecutive elements in array at specific Index in Javascript

I have two arrays like this,

var firstArray = ['one','two','three','four','five','six','seven'];
var secondArray =['1','2','3','4','5','6','7','8'];

I have to insert second array elements into first array like this,

var combinedArray =['one','two','three','1','2','four','five','six','3','4','seven','5','6','7','8']

I know that I could splice and insert at specific index for one element. However I am confused how exactly to achieve this pattern. Could any one help me out with this?

like image 675
akila arasan Avatar asked Dec 09 '25 08:12

akila arasan


1 Answers

You could use a pattern for the chunks and slice the wanted length for a new array.

var firstArray = ['one', 'two', 'three', 'four', 'five', 'six', 'seven'],
    secondArray = ['1', '2', '3', '4', '5', '6', '7', '8'],
    data = [firstArray, secondArray],
    pattern = [3, 2],
    result = [],
    i = 0,
    l = data.reduce(function (r, a) { return Math.max(r, a.length); }, 0);

while (i < l) {
    pattern.forEach(function (a, j) {
        result = result.concat(data[j].slice(i * a, (i + 1) * a));
    });
    i++;
}

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 112
Nina Scholz Avatar answered Dec 10 '25 22:12

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!