How to insert an array into array at a specific index in JavaScript

2 Answers

0 votes
var arr = ["a", "b", "c", "d", "e"];
var barr = ["X", "Y", "Z"];

Array.prototype.insert = function(index) {
  index = Math.min(index, this.length);
  arguments.length > 1
    && this.splice.apply(this, [index, 0].concat([].pop.call(arguments)))
    && this.insert.apply(this, arguments);
  return this;
};

arr = arr.insert(2, "W", "V", barr, "T").join("-");
    
document.write(arr);
    

/*
run:

a-b-W-V-X-Y-Z-T-c-d-e
  
*/

 



answered Jul 25, 2017 by avibootz
0 votes
var arr = ["a", "b", "c", "d", "e"];
var barr = ["X", "Y", "Z"];

Array.prototype.insert = function(index) {
  index = Math.min(index, this.length);
  arguments.length > 1
    && this.splice.apply(this, [index, 0].concat([].pop.call(arguments)))
    && this.insert.apply(this, arguments);
  return this;
};

arr = arr.insert(3, barr).join(" ");
    
document.write(arr);
    

/*
run:

a b c X Y Z d e
  
*/

 



answered Jul 25, 2017 by avibootz

Related questions

...