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?

3
  • 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 Commented Aug 19, 2014 at 17:12
  • 3
    You might want to look at Array.splice() developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… . Commented Aug 19, 2014 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. Commented Aug 19, 2014 at 17:15

2 Answers 2

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]
Sign up to request clarification or add additional context in comments.

1 Comment

[position, 0].concat(source): the clever solution I was looking for. Beautiful!
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?

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.