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

var myArray = ["Sameera","Sanath"];

//Add element to array

//Check already contains and add an element
if ($.inArray("Jaya" ,myArray) == -1){


//Remove element from array

var index = $.inArray("Sanath", myArray);
myArray.splice(index, 1);

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

//Get comma separated string from array
var myArray = ["Sameera","Sanath","Jaya"];
var myUsers = myArray.join(",");

No comments:

Post a Comment