Skip to content
Advertisement

How to combine 2 arrays with the condition that 2 and 5 values will be from the second array?

There are two arrays:

JavaScript

How to merge to get like this;

$newArr = [1, 2, 3, 4, 5];

Now displays through one, this option is not suitable.

JavaScript

Here is another example. Tthe values can be different in the array.

JavaScript

Again for this example it is necessary that the values from the second array always be at 2 and 5 positions in the new array:

JavaScript

Advertisement

Answer

You can use array_splice to merge the arrays in the intended way to the specific indices:

JavaScript

Demo 1:

Using original data:

JavaScript

https://3v4l.org/dAMav

Demo 2:

Using second set of data:

JavaScript

https://3v4l.org/Xhl3K

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement