1

Say I have two arrays:

var numbers = [1,3,5,7,9,11];
var letters = ['a','b','c'];

And say I have another reference to the numbers array:

var anotherRef = numbers;

I would like to insert one into the other in a way that modifies the existing array, so that after the operation, anotherRef === numbers.

If I didn't need to maintain the original array, I would do this:

function insert(target, source, position) {
  return target.slice(0, position).concat(source, target.slice(position));
}

The problem is, after an insert with this method, the two references point at different arrays:

numbers = insert(numbers, letters, 3);
numbers !== anotherRef; // sadly, true.

If I were adding to the end of the array, I could do this, which is kind of slick:

function insertAtEnd(target, source) {
  Array.prototype.push.apply(target, source);
}

Is there a nice way to insert multiple values in place in a JS array?

SimplGy
  • 20,079
  • 15
  • 107
  • 144
  • I'm confused by the first bit: "after the operation, `anotherRef === numbers`". Isn't this the case *before* any operation? Since they point to the same array, any operation performed on either will be reflected by either reference – Andrew Whitaker Aug 19 '14 at 17:12
  • 3
    You might want to look at `Array.splice()` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice . –  Aug 19 '14 at 17:13
  • @AndrewWhitaker, Yep, it's the case before, and I need it to be the case after, too. The trouble is concat returns a new array and so does slice. `splice` doesn't, but it doesn't handle multiple arguments in an array. – SimplGy Aug 19 '14 at 17:15

2 Answers2

2

It looks like you're looking for the splice method:

function insert(target, source, position) {
    Array.prototype.splice.apply(target, [position, 0].concat(source));
    return target;
}
var numbers = [1,3,5,7,9,11];
var letters = ['a','b','c'];

insert(numbers, letters, 3);
console.log(numbers);
>> [1, 3, 5, "a", "b", "c", 7, 9, 11]
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
1

Working example: http://jsfiddle.net/0mwun0ou/1/

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)

console.log(anotherRef)

I never touched anotherRef, but on that example the output is:

[1, "a", "b", "c", 3, 5, 7, 9, 11] 

For an explanation how to use an array as the third argument of splice check: Is there a way to use Array.splice in javascript with the third parameter as an array?

Community
  • 1
  • 1
bitoiu
  • 6,893
  • 5
  • 38
  • 60