2

Suppose I have an array like this:

['foo', 'bar', 'baz']

And I wanted to insert 3 elements starting at position 2:

['foo', 'bar', null, null, null, 'baz']

I could use Array.prototype.splice() like this:

['foo', 'bar', 'baz'].splice(2, 0, null, null, null);

However, I'm looking to insert an arbitrary number of elements, or for the purposes of what I'm doing, repeating the previous element an arbitrary amount of times is also fine. My desired result:

// When position = 2 and n = 3
['foo', 'bar', null, null, null, 'baz']

// Alternatively, repeat the element at position-1:
['foo', 'bar', 'bar', 'bar', 'bar', 'baz']

How would I do this? jQuery is acceptable but I'm not sure how it would help.

1 Answer 1

1

I can propose a solution when undefined values are inserted rather than null:

var a = ['foo', 'bar', 'baz']
a.splice.apply(a, [2, 0].concat(Array(3)));
console.log(a); // ["foo", "bar", undefined, undefined, undefined, "baz"] 

You can control number of items to be inserted with parameter passed into Array constructor.

Sign up to request clarification or add additional context in comments.

1 Comment

I guess undefined will have to do for now.

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.