Click here to Skip to main content
15,878,809 members
Articles / All Topics

Find And Exclude Element From Array

Rate me:
Please Sign up or sign in to vote.
4.59/5 (8 votes)
5 Aug 2015CPOL2 min read 8.1K   3   4
In this post, we will discuss about finding and excluding element from JQuery Array.

In this post, we will discuss about finding and excluding element from JQuery Array. We all worked in a JQuery. Sometimes, we work in JQuery Arrays too. Right? Consider we have an array, and in that array we need to exclude a particular element and create a new array without excluded element. What we will do? We will use a for loop and just loop through the array, apply some conditions and if a criteria matches, we will do some operation right? Here I am going to share with you another way that we can achieve this by using a function called grep in JQuery. Normally grep function acts as each in JQuery.

Background

I am working on a client side application where there are lots of client side arrays and variables. We handle our entire client side processes by using JQuery. I usually go through the operation of finding and removing array elements using JQuery. I thought it would be better if I share some knowledge about that here. I hope someone will find it useful.

Using the Code

To start with, you need to include jquery reference.

JavaScript
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>

Now, we need an array right? Consider the following is our array.

JavaScript
var myArray = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']

Next, we will formulate this array to an HTML table, so that the visualization will be perfect. To do this, we will have a function, which will just convert the array element to an HTML table. Following is our function body.

JavaScript
function buildTable(array,message){
	      var html='<table><caption>'+message+'</caption><tr>';
		  for(var i=0;i<array.length;i++)
		  {
			html+='<td>'+array[i]+'</td>';
		  }
		  html+='</tr></table>';
		  $("#body").html(html);
	   }	 

As you can see, the parameters for this function are, an array and a caption message.
Now, we need to call this function right?

JavaScript
 var myArray = ['Monday','Tuesday',
'Wednesday','Thursday','Friday','Saturday','Sunday']			
			var message="My Array Elements Before Removing";
			buildTable(myArray,message);  

Style out HTML table by giving the preceding styles.

CSS
<style>
         tr{
            border:1px solid #ccc;
         }
         td{
            border:1px solid #ccc;
            padding: 10px;
         }
         #body{
           margin: 30px;
         }
         #click{
           margin: 30px;
           cursor:pointer;
         }

     </style>

So, our output will be as follows:

Exclude_or_remove_array_element_from_array

Now, we need to fire a click event in which we will find out which element is to be excluded from the array, and finally assign new element set to our existing array.

XML
<a hrefe="#" id="click">Click To Remove</a>
JavaScript
$("#click").click(function(){
				var message="My Array Elements After Removing";
				var excludedElement = ['Thursday'];
				myArray = jQuery.grep(myArray, function(value) {
				return value != excludedElement;
			    });
			    buildTable(myArray,message);
			});

Here, we are finding the element ‘Thursday’ which we saved to a variable as follows:

JavaScript
var excludedElement = ['Thursday'];	 

Now our real here is jQuery.grep, which returns our new array with filtered data.

JavaScript
return value != excludedElement;

And then, we are calling our buildTable function to formulate our new array to an HTML table. Once we call it, we will get an output as follows:

Exclude_or_remove_array_element_from_array_after

Complete Code

XML
<html>
   <head>
      <title>Remove Elements From An Array using JQuery- Sibeesh Passion</title>
      <style>
		  tr{
		     border:1px solid #ccc;
		  }
		  td{
			 border:1px solid #ccc;
			 padding: 10px;
		  }
		  #body{
		    margin: 30px;
		  }
		  #click{
		    margin: 30px;
			cursor:pointer;
		  }
		  
      </style>
      <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
   </head>
   <body>
   <a hrefe="#" id="click">Click To Remove</a>
   <div id="body"></div>
      <script>	  
       $(document).ready(function(){
		    var myArray = ['Monday','Tuesday','Wednesday',
		    'Thursday','Friday','Saturday','Sunday']			
			var message="My Array Elements Before Removing";
			buildTable(myArray,message);
			
			$("#click").click(function(){
				var message="My Array Elements After Removing";
				var excludedElement = ['Thursday'];
				myArray = jQuery.grep(myArray, function(value) {
				return value != excludedElement;
			    });
			    buildTable(myArray,message);
			});
	   });
	   function buildTable(array,message){
	      var html='<table><caption>'+message+'</caption><tr>';
		  for(var i=0;i<array.length;i++)
		  {
			html+='<td>'+array[i]+'</td>';
		  }
		  html+='</tr></table>';
		  $("#body").html(html);
	   }
      </script>
	  
   </body>
</html> 	 

Demo

Please find out the demo in jsfiddle here: Exclude or remove elements

Conclusion

I hope you liked this tip. Please share your feedback. It is always welcome. Thanks!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Germany Germany
I am Sibeesh Venu, an engineer by profession and writer by passion. I’m neither an expert nor a guru. I have been awarded Microsoft MVP 3 times, C# Corner MVP 5 times, DZone MVB. I always love to learn new technologies, and I strongly believe that the one who stops learning is old.

My Blog: Sibeesh Passion
My Website: Sibeesh Venu

Comments and Discussions

 
GeneralMy vote of 5 Pin
Mahsa Hassankashi12-Sep-15 9:51
Mahsa Hassankashi12-Sep-15 9:51 
GeneralRe: My vote of 5 Pin
Sibeesh Passion13-Sep-15 19:07
professionalSibeesh Passion13-Sep-15 19:07 
Thank you so much Smile | :)
==================!!!====================!!!========================
So much complexity in software comes from trying to make one thing do two things.
Kindest Regards
Sibeesh
http://sibeeshpassion.com/

QuestionGood Article Pin
Santhakumar Munuswamy @ Chennai11-Sep-15 21:41
professionalSanthakumar Munuswamy @ Chennai11-Sep-15 21:41 
AnswerRe: Good Article Pin
Sibeesh Passion11-Sep-15 21:43
professionalSibeesh Passion11-Sep-15 21:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.