3

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?

5
  • how do you decide the index? Commented Mar 15, 2017 at 12:06
  • I have to insert after every three elements in first array .I thought may be by looping through I could achieve this .But I was unable to do so Commented Mar 15, 2017 at 12:08
  • Same question. After how many elements of first array you are supposed to insert the element of the second array?? and how many elements of the second array to be inserted, Is it always 3 element from first array then 2 element of the second array? Commented Mar 15, 2017 at 12:08
  • yes it always after three elements in the first array .But if the length of the first array is less than three i need to append the remaining elements in the second array with the first array Commented Mar 15, 2017 at 12:11
  • 1
    You have six twice in your example output Commented Mar 15, 2017 at 12:15

4 Answers 4

1

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; }

Sign up to request clarification or add additional context in comments.

Comments

0

You can actually splice more than one item:

firstArray.splice(3, 0, "1", "2");

Comments

0

You can create two variables i and j and increment first one by 3 that you will use to slice first array and increment the second one by 2 and you will use that one to slice second array. If the i + 3 > a.length you will concat rest of elements in b array to result.

var a = ['one','two','three','four','five','six','seven'];
var b = ['1','2','3','4','5','6','7','8'];
var r = [], i = 0, j = 0

while(i < a.length) {
  r.push(...a.slice(i, i + 3), ...b.slice(j, i + 3 < a.length ? j + 2 : b.length))
  i += 3, j += 2
}

console.log(r)

Comments

0

a more granular approach:

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

var combinedArray = flatten(zip(
  toGroupsOf(3, firstArray), 
  toGroupsOf(2, secondArray)
));

console.log(combinedArray);


//a the utilities for that

function isUint(value){
  return value === (value >>> 0)
}

function toGroupsOf(length, arrayOrString){
  if( !isUint(length) || !length  ) 
    throw new Error("invalid length " + JSON.stringify(length));
  
  return Array.from(
    { length: Math.ceil(arrayOrString.length / length) }, 
    (v,i) => arrayOrString.slice(i*length, (i+1)*length)
  );
}

function zip(...arraysOrStrings){
  var numColumns = arraysOrStrings.length,
      lengths = arraysOrStrings.map(item => (item && +item.length) || 0),
      x=0, y=0;
  return Array.from(
    { length: lengths.reduce((a,b)=>a+b, 0) },
    function(v,i){
      for(var safety = numColumns+1; safety--;){
        if(y < lengths[x])
          return arrays[x++][y];
        else if(++x >= numColumns)
          x=0, ++y;
      }
      throw new Error("something went wrong, this line should have never been reached");
    }
  )
}

function flatten(array){
  return [].concat.apply([], array);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.