Javascript Data Type How to - Insert an array in the middle of an existing array








Question

We would like to know how to insert an array in the middle of an existing array.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--from   w ww  .  j av a 2s. c  om-->
function insert(target, source, position) {
  Array.prototype.splice.apply(target, [position,0].concat(source));
}
var numbers = [1,3,5,7,9,11];
var letters = ['a','b','c'];
var anotherRef = numbers;
insert(numbers, letters, 1);
document.writeln(anotherRef);
</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: