1

I have an array

array1 = [1,2,3,6,7,8]

array2 = [40,50]

How can i push items in array2 to array1 to get a result

 result = [1,2,3,40,50,6,7,8];

keep in mind its not a simple concatination, need to insert the scecond array in specific index.

array1.splice(3, 0, array1 ); => splice doesnt accept another array.

How can i enter items in diffrent array to a specific index?

Im trying this in angular

array1 .splice(3, 0,...array2);

and getting the im getting spread array doesn't support in tslib

4
  • 2
    array1.splice(3, 0, ...array2); will do the job, although this will alter array1, so I'm assuming you want array1 to be result. Of course, I also assume that your environment supports the spread operator. Commented Jul 8, 2020 at 7:46
  • 1
    Following @briosheje's comment, I suggest you read about spread operators in general - they were introduced exactly to aid for these cases: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jul 8, 2020 at 7:47
  • Do you want to alter array1 or do you want to create a new array that is the result of the concatenation? Commented Jul 8, 2020 at 7:49
  • the im getting spread array doesn't support in tslib Commented Jul 8, 2020 at 7:50

3 Answers 3

1

var array1 = [1,2,3,6,7,8]

var array2 = [40,50]


function cobmine(arr1,arr2,index){
  var arr3=arr1.splice(0,index);
  var arr4=arr1.splice(-index);
  return arr3.concat(arr2).concat(arr4)
}

var result=cobmine(array1,array2,3);
console.log(result);

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

Comments

1

Assuming your env does not support spread syntax for some reason you could stick to ES5 apply technique.

array1 = [1,2,3,6,7,8]

array2 = [40,50]

array1.splice.apply(array1, [3, 0].concat(array2))

console.log(JSON.stringify(array1))

Comments

0

You can use below code to add array at a specific index

const arr1 = [1,2,3,6,7,8]
const arr2 = [40,50]
const index = 3

const newArr = [
    ...arr1.slice(0, index),
    ...arr2,
    ...arr1.slice(index + 1),
]
// [1,2,3,40,50,6,7,8]

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.