Harry
Harry

Reputation: 13329

Remove objects from JS array upto a certain index

I have an array:

array = [S1,S2,S3,S4_a,S4_b,S5_a,S5_b,S5_c etc....]

How can I delete all the objects from the last object down to what ever index I give it ?

array.delte(last:S3)

So, I would like to to delete downto S3, so everything after it must be deleted

new_array = [S1,S2,S3]

Upvotes: 0

Views: 681

Answers (4)

Andrew D.
Andrew D.

Reputation: 8220

Deleting all after index:

var index=3;
var arr1=['a','b','c','d','e','f','g'];
arr1.length=index; // now arr1 contains ['a','b','c']

Deleting all before index:

var index=3;
var arr1=['a','b','c','d','e','f','g'];
var arr2=arr1.slice(index); // now arr2 contains ['d','e','f','g']; arr1 remains unchanged

Upvotes: 0

n3rd
n3rd

Reputation: 6089

var a = [1, 2, 3, 4, 5, 6];

a = a.splice(0, 3);
// a is now [1, 2, 3]

or, if you don't know the position of 3:

a = a.splice(0, a.indexOf(3) + 1);

Be aware though, that some browsers do not implement Array.indexOf so consider using a library such as jQuery or prototype.

Upvotes: 2

sje397
sje397

Reputation: 41862

It think you want splice:

array.splice(0, index);

Upvotes: 2

DhruvPathak
DhruvPathak

Reputation: 43265

Use javascript array splice function , or array slice function. see : http://jsfiddle.net/

var origArray = new Array('a','b','c','d','e','f','g');
var myIndex = 4;
var origArray = origArray.slice(0,myIndex);  // is now ['a','b','c','d']

Upvotes: 1

Related Questions