madc
madc

Reputation: 1744

Adding new content to an javascript array

I have a numeric javascript array, that contains several objects with geodata in it. What I need to do is, to add a dynamic count of new objects after a specific object in this array.

I know, that there is the splice function, but i do not know, how to make the count of new objects variable.

myArray.splice( pos, 0, ... );

What am I getting wrong?

Upvotes: 0

Views: 60

Answers (1)

Yoshi
Yoshi

Reputation: 54649

Hope I understood what you meant.

var
  oldA = [1, 2, 3],
  newA = [4, 5];

oldA.splice.apply(oldA, (function (index, howMany, elements) {
  // this is actually building the arguments array (2nd parameter)
  // for the oldA.splice call
  elements = elements.slice();
  elements.splice(0, 0, index, howMany);

  return elements;
}(/*index to insert at*/ 2, /*howMany to remove*/ 0, /*elements to insert*/ newA)));

console.log(oldA, newA); // [1, 2, 4, 5, 3] [4, 5]

Upvotes: 1

Related Questions