Add and remove elements from JavaScript array

Here I show how to add ,remove elements and get a comma separated string from JavaScript array

 

Add / Remove elements from array

  1. var myArray = ["Sameera","Sanath"];  
  2.   
  3. //Add element to array  
  4. myArray.push("Amila");  
  5.   
  6.   
  7. //Check already contains and add an element  
  8. if ($.inArray("Jaya" ,myArray) == -1){  
  9.     myArray.push("Jaya");  
  10. }  
  11.   
  12. console.log(myArray);  
  13.   
  14.   
  15. //Remove element from array  
  16.   
  17. var index = $.inArray("Sanath", myArray);  
  18. myArray.splice(index, 1);  
  19.   
  20. console.log(myArray);      
Here I used Jquery  index = $.inArray("Sanath", myArray); to get index of the element. We can also get the index by index = myArray.indexOf("Sanath"); .But indexOf does not work on IE 8 and below.

Get a comma separated string from array

  1. //Get comma separated string from array  
  2. var myArray = ["Sameera","Sanath","Jaya"];  
  3. var myUsers = myArray.join(",");  
  4. console.log(myUsers);  

No comments:

Post a Comment