user1765862
user1765862

Reputation: 14165

remove elements from array knowing number of previously added elements

If I have array in javascript and I want how many elements I added before using push how can I remove from array knowing it's lenght and number of elements added before?

//toAdd has for example 10 elements
 $.each(toAdd, function (index, item) {
   myArr.push(item);
  });

Upvotes: 0

Views: 49

Answers (2)

Parthipan Subramaniam
Parthipan Subramaniam

Reputation: 372

By checking the length using length property. Use push method to add element and use splice method to remove the values based on the index or use pop to remove top element.

Upvotes: 1

Jai
Jai

Reputation: 74738

You have to store the length of the array before doing any .push() into:

  var arrLen = myArr.length;

  //toAdd has for example 10 elements
  $.each(toAdd, function (index, item) {
     myArr.push(item);
  });

Now if you want to reset it, just set the length:

myArr.length = arrLen;

Upvotes: 1

Related Questions