I have two array of objects. Something like this:
var arrayA = [
{
type: 'card',
id: 1
},
{
type: 'card',
id: 2
},
{
type: 'card',
id: 3
},
{
type: 'card',
id: 4
},
{
type: 'card',
id: 5
},
];
var arrayB = [
{
type: 'pro-tip',
id: 10
},
{
type: 'pro-tip',
id: 11
},
];
I want to merge these two arrays of objects, but on a specific order. Basically, what I want is that, after each N number of elements from arrayA, I want to add one element from arrayB. If N == 2 The final array would look like this:
var finalArray = [
{
type: 'card',
id: 1
},
{
type: 'card',
id: 2
},
{
type: 'pro-tip',
id: 10
},
{
type: 'card',
id: 3
},
{
type: 'card',
id: 4
},
{
type: 'pro-tip',
id: 11
},
{
type: 'card',
id: 5
},
];
Probably it is not difficult to do something like this, but I'm looking for the most elegant way to build a helper function to do that.
Edit:
Here's the function I created. It seems like it works, but there might be a simpler way to do it:
function mergeWithSteps( arrayA, arrayB, nSteps, nElementsToAdd ) {
var finalArray = [],
stepsCount = 0,
elementsToAddCount = 0,
arrayBNumberOfElements = arrayB.length;
arrayA.forEach( function( obj ) {
finalArray.push( obj );
stepsCount++;
if( stepsCount == nSteps && elementsToAddCount < arrayBNumberOfElements ) {
finalArray.push( arrayB[ elementsToAddCount ] );
elementsToAddCount++;
stepsCount = 0;
}
} );
return finalArray;
}