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?
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With