rink.attendant.6
rink.attendant.6

Reputation: 46228

Insert arbitrary number of elements into array

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.

Upvotes: 2

Views: 246

Answers (1)

dfsq
dfsq

Reputation: 193261

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.

Upvotes: 1

Related Questions