Wednesday, 18 August 2021

jQuery remove duplicates from array of strings

 Hi guys, in this post we will see how to remove duplicates from array of strings using jquery.

we will use this jquery array in this example:-

var Friends=["SAM","john","sam","Maddy","David","JOHN"];

This array has duplicate element such "Sam","john". We want to remove this duplicate elements using jquery.

Let's start

1)Open your editor.

2) Add <html>,<head>,<script> and <body> tag. Then add jquery CDN link  in head section as below:-

<html>

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script type="text/javascript">

</script>

</head>

<body>

   </body>

</html>

3)Add following code to find and remove duplicates from array of strings:-

<script type="text/javascript">

// Add document ready function to check whether DOM is loaded.

$(document).ready(function(){

// Declare and initialize jquery array 

var Friends=["SAM","john","sam","Maddy","David","JOHN"];

// logic to select only unique string elements

var UniqueArray=Friends.filter(function(element,index,self){

return index!=self.indexOf(element.toLowerCase());

});

// Show unique elements from array in alert

alert(UniqueArray);

});

</script>

Full code:-

<html>

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script type="text/javascript">

$(document).ready(function(){

var Friends=["SAM","john","sam","Maddy","David","JOHN"];

var UniqueArray=Friends.filter(function(element,index,self){

return index!=self.indexOf(element.toLowerCase());

});

alert(UniqueArray);

});

</script>

</head>

<body>

 </body>

</html>

Screenshot of code:-

jQuery remove duplicates from array of strings,#jQuery,

Output:-

jQuery remove duplicates from array of strings,#jQuery,





No comments:

Post a Comment