Saturday, January 17, 2009

How to remove a value from array in javascript ?

Yesterday I was writing javascript and I came across a problem where I had to remove a value from a array in javascript . As usual I tried Array.remove[index] . But it did not work . So how to remove a element from Javascript array ?

Its quite simple . There are two functions which serves your purpose .

splice :

Usage : If you know index of the element / elements to be removed ,
ArrayName.splice(index,Noofelementstoberemoved) ;

E.g : If you want to remove single element from second position in Array=['one','two','three','four','five'];
use Array.splice(1,1) . The result will be ['one','three','four','five']; .

Remove :
If you dont know the index of a particular element to be removed but you know the value of it ,
You can use remove .

Usage : Array.remove('Valuetoberemoved') ;

E.g . To remove fifth element in the above array , use Array.remove('five') ;