In this post I will be explaining different array operations .
1. How to declare an array
a.Declare a blank array
var persons= [];
b.Declaring array with values
var persons= [“Ram”,”Khalid”,”Saurav”, “Kunal”, “Ashiq”, “Pradeep”];
2. How to get length of an array
arrayList.length
Example :
var persons= [“Ram”,”Khalid”,”Saurav”, “Kunal”, “Ashiq”, “Pradeep”];
alert(persons.length); //6
3. How to traverse am array
for(var i=0;i<persons.length;i++)
alert(persons[i]);
4. How to add a new element to the array
persons.push(‘Gopal’);
5. How to sort an array
listName.sort()
Example :
< div id=”arrSort” >
var list =[ ‘a’, ‘d’, ‘k’, ‘c’, ‘p’, ‘f’]
$(‘#arrSort’).append(‘<br/><br/> Before sorting array list is : ‘ +list .join(“,”));
list.sort()
$(‘#arrSort’).append(‘<br/> After sorting array list is :’+list .join(“,”));
Result :
Before sorting array : a,d,k,c,p,f
After sorting array list is :a,c,d,f,k,p
6. How to search an element in array
jQuery.inArray( value, array [, fromIndex] )
Example :
var list =[ ‘a’, ‘d’, ‘k’, ‘c’, ‘p’, ‘f’]
alert(jQuery.inArray(“a”,list)); //Returns index value of ‘a’ i.e. 0
alert(jQuery.inArray(“f”,list)); //Returns index value of ‘f’ i.e. 5
alert(jQuery.inArray(“z”,list)); //Returns -1
alert(jQuery.inArray(“p”,list,2)); //’p’ is an element which exists after index 2
//returns 4
alert(jQuery.inArray(“d”,list,2)); //’d’ is in the array but not at or after index 2, so -1
7. How to remove last element from an array
arrayList.pop();
Example :
< div id=”arrRemove” >
persons= [
“Ram”,
“Khalid”,
“Saurav”,
“Kunal”,
“Ashiq”,
“Pradeep”
];
$(‘#arrRemove’).append(‘<br/><br/> Before Removing last element array list : ‘+persons.join(‘,’));
persons.pop() ;
$(‘#arrRemove’).append(‘<br/> After Removing last element array list : ‘+persons.join(‘,’));
8. How to remove specific element from an array
By using jQuery.grep() function we can remove specific element from list
< div id=”arrSpecific” >
var age = [20,24,70,28,22];
var remItem=28;
$(‘#arrSpecific’).append(‘
Before Removing element array list : ‘+age .join(‘,’));
age = jQuery.grep(age, function (value) {
return value != remItem;
});
$(‘#arrSpecific’).append(‘
After last element array list : ‘+age .join(‘,’));
Click here for demo .