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
myArray.push("Amila");


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

console.log(myArray);


//Remove element from array

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

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

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

No comments:

Post a Comment