-2

what is an elegant way to add an array of element after the selected index ?

let arr1 = ["a","b","c"]
let arr2 = ["1","2","3"]

function concat(arr1, arr2, atIndex){
  for(let i = 0; i < arr2.length; i++){
    arr1.splice(atIndex+i, 0, arr2[i]);
  }
  return arr1;
}

concat(arr1, arr2, 2) //  ["a", "b", "1", "2", "3", "c"]
concat(arr1, arr2, 0) //  ["1", "2", "3", "a", "b", "c"]
Bobby
  • 4,372
  • 8
  • 47
  • 103
  • 1
    please add some examples of the result. – Nina Scholz May 16 '19 at 09:02
  • 1
    Possible duplicate of [Javascript - insert an array inside another array](https://stackoverflow.com/questions/7032550/javascript-insert-an-array-inside-another-array) – adiga May 16 '19 at 09:06
  • Four gold badges answering the exact same thing mentioned in the duplicate. [This is fine](https://i.imgur.com/c4jt321.png) – adiga May 16 '19 at 09:12

4 Answers4

3

Use splice as following.

let arr1 = ["a","b","c"];
let arr2 = ["1","2","3"];
arr1.splice(1, 0, ...arr2);
console.log(arr1);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
1

Use concat and slice:

let arr1 = ["a", "b", "c"]
let arr2 = ["1", "2", "3"]

function concat(arr1, arr2, atIndex) {
  return arr1.slice(0, atIndex).concat(arr2).concat(arr1.slice(atIndex));
}

console.log(concat(arr1, arr2, 1));
.as-console-wrapper { max-height: 100% !important; top: auto; }
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

You can pass all the elements to splice() using spread syntax.

let arr1 = ["a","b","c"]
let arr2 = ["1","2","3"]

const concat = (a1,a2,ind) => {
    let res = [...a1];
    res.splice(ind,0,...a2);
    return res;
};

console.log(concat(arr1,arr2,1))
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

You could get a copy from the first array and splice the spreaded second array.

function concat([...arr1], arr2, atIndex){
    arr1.splice(atIndex, 0, ...arr2);
    return arr1;
}

var arr1 = ["a","b","c"],
    arr2 = ["1","2","3"];

console.log(...concat(arr1, arr2, 2)); //  ["a", "b", "1", "2", "3", "c"]
console.log(...concat(arr1, arr2, 0)); //  ["1", "2", "3", "a", "b", "c"]
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392