Working with array in jquery

working with array in jquery

Hello friends, welcome to my today’s post on jQuery. Today we are going to learn about array manipulation in jQuery. We know jQuery is one of the most popular JavaScript framework in web development world. Also their mobile framework (jQuerymobile) has got vast popularity ever in JavaScript framework lists which basically build on jQuery framework. So, If you know jQuery then you can easily move on jQuery Mobile Framework for mobile based web development,

Anyway, I love to work with jQuery, because it is so much simpler, easy to understand and a lots of open source plugins developed for jQuery. So, today we are going to learn some quick and useful scripts for jQuery. Let’s get started –

– Create an Array In jQuery:

Remember on thing, jQuery framework build on JavaScript. So, we can write regular JavaScript code in jQuery framework. First we are going to create a simple array using JavaScript syntax. Here goes array deceleration code –

var my_arrray = [ ];

That code means, this is an one dimensional array and their is no index defined in that array. Now, I like to create an unordered lists using HTML syntax like below –

<ul id="website-lists">
    <li id="website1">Google.com</li>
    <li id="website2">Facebook.com</li>
    <li id="website3">Yahoo.com</li>
</ul>

Now, we are going to create that “unordered lists” using jQuery. Here goes snippets for create unordered list.

var website_lists = $('#website-lists');
website_lists.children("li").each(function(){
    var wId = $(this).attr("id");
    var website = $(this).text();
    myArray.push({
        'id':wId,
        'name':website
    });
});

Here “push” is a function that insert “key” and “value” as an array item in to unordered lists. Very easy!

– How to show array data using jQuery:

var result = $("body");
$.each(myArray,function(i,v){
    result.append($('

‘).hide(). text(“Name:”+v.name+”with Id”+v.id).show(“slow”) ); });

– Comparing and removing data from array :

var removeMe;
$.each(myArray,function(i,v){
    if(v.name=="Yahoo.com"){
        removeMe = i;
    }
});
myArray.splice(removeMe,1);

we can easily remove any item from an unordered lists. By using this code we can easily remove items. $.each function take all items from my array and it works like “for loop” after that it compare item name is “Yahoo.com” or not. If it found then item will removed from this unordered lists. It’s so simple!

I hope this array tutorial will be a helpful part in your work. Was this information useful? What other tips would you like to read about in the future? Share your comments, feedback and experiences with us by commenting below!

Share It

Related Posts