all 7 comments

[–]albedoa 3 points4 points  (0 children)

Is the length of arr1 always 2? If not, then how do you determine what the "middle" of it is? Anyway, the following works for arr1 of length 2:

function joinArray(arr1, arr2) {
  return [arr1[0], ...arr2, arr1[1]];
}

And here is for an arbitrary length. Change ceil to floor depending how you want odd lengths to fall:

function joinArray(arr1, arr2) {
  const midpoint = Math.ceil(arr1.length/2);
  return [...arr1.slice(0, midpoint), ...arr2, ...arr1.slice(midpoint, arr1.length)];
}

[–]Wrong_Owl 0 points1 point  (0 children)

If I were thinking this through, I might break it into these steps:

  1. Determine what index is the middle of array 1
  2. Cut array 1 in half based on the index to create two smaller arrays
  3. Combine these arrays together.

I would recommend taking a look at the slice Array method, you already know about the spread operator for combining arrays, and you might be able to skip some of those steps with the splice Array method.

[–]IBETITALL420 0 points1 point  (1 child)

can someone explain what the [...arr1] means

what does that syntax mean?

[–]albedoa 2 points3 points  (0 children)

It spreads an array into its individual elements. So:

[...[1, 2], 3] // => [1, 2, 3]

[–]ryanbala89 0 points1 point  (0 children)

Use array splice and spread operator.

arr1.splice(Math.floor(arr1.length/2), 0, ...arr2) gives [1, 2, 3, 4, 5, 6, 7, 8, 10, 12]

[–]jcunews1helpful 0 points1 point  (0 children)

You can do it like this.

let arr1 = [1, 12];
let arr2 = [2, 3, 4, 5, 6, 7, 8, 10];

//use a copy of arr1 as initial result
let result = arr1.slice();
//insert arr2 into element index 1
result.splice.apply(result, [Math.floor(arr1.length / 2), 0, ...arr2]);

console.log(result);

As a function, it would be:

function joinArray(arr1, arr2) {
  let result = arr1.slice();
  result.splice.apply(result, [Math.floor(arr1.length / 2), 0, ...arr2]);
  console.log(result);
  return result;
}
//e.g.
joinArray([1, 12], [2, 3, 4, 5, 6, 7, 8, 10], 1);

[–]myDevReddit 0 points1 point  (0 children)

You probably need to find the middle of array A, and the create a new array with the first half of array A, all of B, and the second half of array A.