Creating Arrays in jQuery
At the very basic level you can create an empty array like this
I like to use empty arrays because I will fill them programmatically with HTML that is available on the page. Let’s say you have created a list from a database that looks like this
2 |
< li id = "user1" >Jim</ li >
|
3 |
< li id = "user2" >Mike</ li >
|
4 |
< li id = "user3" >Jake</ li >
|
Filling an Empty Array with data from an Unordered List
Using the list above we can put the users ID and Names into the array for use later
02 |
var userList = $( '#userList' );
|
03 |
userList.children( 'li' ).each(function() {
|
04 |
var userID = $( this ).attr( 'id' );
|
05 |
var userName = $( this ).text();
|
Display Data in a jQuery Array
Once the data is in the array you will want to make sure it looks good. Here’s how you can show the data in the array quickly.
1 |
var result = $( 'body' );
|
2 |
$.each(myArray, function(i, v) { |
3 |
result.append($( '<p>' ).hide().text( 'Name: ' + v.name + ' with ID: ' + v.id).show( 'slow' ));
|
I am basically creating a P tag for each item in the array and creating text in each paragraph with the information from the array. Using $.each() and .append() functions.
Comparing and Removing from Arrays in jQuery
Let’s say you don’t want to have Jim in the array anymore, we can use the same $.each() along with the .splice() function to accomplish this.
2 |
$.each( myArray, function(i, v) { |
3 |
if ( v.name == 'Jim' ) {
|
7 |
myArray.splice(removeMe, 1 );
|
This is only removing one item, but let’s say you want to compare two arrays and remove all the items in one array from the items in the other array?We are going to create a function that opens the array outside of the $.each() (I’d like to thank Viral Planet for their JavaScript Array Remove an Element post, helped me create this function with the added .name to allow searching by key name)
01 |
function removeByValue(arr, val) { |
02 |
for (var i= 0 ; i<arr.length; i++) {
|
03 |
if (arr[i].name == val) {
|
09 |
var names = [ 'Jim' , 'Fred' ];
|
10 |
$.each( names, function(i, v) { |
11 |
removeByValue(myArray, v);
|
You can just use this function for removing a single item in the array too, I just wanted to show you a couple different ways. We can also update this function a bit and allow you to add the key name yourself.
01 |
function removeByValue(arr, key, val) { |
02 |
for (var i= 0 ; i<arr.length; i++) {
|
03 |
if (arr[i][key] == val) {
|
09 |
var names = [ 'Jim' , 'Fred' ];
|
10 |
$.each( names, function(i, v) { |
11 |
removeByValue(myArray, 'name' , v);
|
Enjoy