0

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?

1 Answer 1

1

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

1 Comment

Thanks, I think you did! I am just giving it a try and report back.

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.