principiorum
principiorum

Reputation: 616

How to merge two arrays and arrange the result by its position?

I have a question how to merge two arrays, but the result should place first array value next to the second one?

Here is what I want to achieve

array1 [1,2,3,4,5,6]

array2 ['+', '-', '/']

the expected result is [1, '+', 2, '-', 3, '/', 4, 5, 6]

notice that if the array is not on same length, it will be put at the bottom

Upvotes: 2

Views: 51

Answers (2)

yochanan sheinberger
yochanan sheinberger

Reputation: 735

Maybe this will work. I did not try it.

var array1 = ["1", "2", "3", "4", "5"];

var array2 = ["+", "-", "/"];

var x = 1;

for (let i= 0; i < array2.length; i++) {
       array1.splice(x, 0, array2[i]);
       x += 2;
}

Upvotes: 1

Hao Wu
Hao Wu

Reputation: 20734

Here's an approach to solve this problem.

const array1 = [1, 2, 3, 4, 5, 6];
const array2 = ['+', '-', '/'];

const maxLength = Math.max(array1.length, array2.length);
const result = [];

for (let i = 0; i < maxLength; i++) {
	if (array1[i] !== undefined)
		result.push(array1[i]);
	if (array2[i] !== undefined)
		result.push(array2[i]);
}

console.log(result);

There's probably a one-liner solution. But this one is simple, efficient enough for my opinion.

Upvotes: 2

Related Questions