0

I have two arrays:

let a = [1, 3, 5];
let b = [2, 4];

I need to put second array into first one after second element, so this is result:

[1, 3, 2, 4, 5]

What is the best way to insert second array into first in es6?

It can be easily solved using concat operation, but I am looking for nice way of doing it in es6.

2
  • I need to put second array at specific position, not in the end. Commented Jan 13, 2017 at 16:29
  • @ruslan5t, please refer to How to ask. It's easier to help if you give us all required criteria at the beginning, instead of editing the question and changing your issue later. Commented Jan 13, 2017 at 16:42

3 Answers 3

4

If you want to insert the second array at specific index, you can use splice function and spread operator.

var a = [1, 3, 5];
var b = [2, 4, 6];

a.splice(2, 0, ...b);

console.log(a); // [1, 3, 2, 4, 6, 5]
Sign up to request clarification or add additional context in comments.

3 Comments

I need to put second array in the middle of first one, not in the end.
@ruslan5t, I updated my answer to better fit your question.
... is not an operator. You could use the term spread argument.
1

Use Array#splice method with spread syntax.

a.splice(2, 0, ...b)

let a = [1, 2, 5];
let b = [3, 4];

a.splice(2, 0, ...b);

console.log(a);

3 Comments

I don't want to sort arrays, I need to put second one in first one at specific position.
... is not an operator. You could use the term spread argument.
@FelixKling : sorry , I just updated :) ... thanks for the correction
0

I think this is the answer you're looking for:

function frankenSplice(arr1, arr2, n) {
    let arr3 = [...arr2];
    arr3.splice(n, 0, ...arr1);
    return arr3;
}

Comments

Your Answer

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