Home > Article > Web Front-end > How to remove array duplicates via js program (ignoring case sensitivity)
This article will introduce you to how to delete duplicates in an array through javascript and ignore case sensitivity. So, do you have your own ideas for implementing this problem?
For example, let me first give you an example array: [1, 2, 2, 4, 5, 4, 7, 8, 7, 3, 6]. There are obviously repeated values in the array, so what do you think? Let’s start by deleting duplicates!
Below I will share with you two js implementation methods for deleting duplicate items in an array. You can refer to it:
The first method:
The code is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script> function removeDuplicates(num) { var x, len=num.length, out=[], obj={}; for (x=0; x<len; x++) { obj[num[x]]=0; } for (x in obj) { out.push(x); } return out; } var Mynum = [1, 2, 2, 4, 5, 4, 7, 8, 7, 3, 6]; result = removeDuplicates(Mynum); console.log(Mynum); console.log(result); </script> </body> </html>
The result is as shown below:
Note: The push() method can add one or more to the end of the array element and returns the new length; the new element will be added at the end of the array; this method changes the length of the array; use the unshift() method to add elements at the beginning of the array.
Second method:
The code is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script> //从JavaScript数组中删除重复项 const nums = [1, 2, 2, 3, 1, 2, 4, 5, 4, 2, 6]; console.log([...new Set(nums)]) </script> </body> </html>
The result is as follows:
Note: Removing duplicates from an array in JavaScript can be done in many ways, such as using Array.prototype.reduce(), Array.prototype.filter() or even a simple for loop; but there is an easier option, JavaScript's built-in Set object is described as a set of values, each of which can appear only once. Set objects are also iterable, so they can be easily converted to arrays using the spread (...) operator.
Here I recommend reading the article "Introduction to Set Object in JavaScript (With Examples)" "Introduction to Common Methods of Expansion Operators in JavaScript" .
Finally, I would like to recommend to you the latest and most comprehensive "javascript basic tutorial" ~ Come and learn!
The above is the detailed content of How to remove array duplicates via js program (ignoring case sensitivity). For more information, please follow other related articles on the PHP Chinese website!