Home > Web Front-end > JS Tutorial > Example of how to remove duplicate values ​​from an array using JS

Example of how to remove duplicate values ​​from an array using JS

高洛峰
Release: 2017-02-20 16:31:41
Original
1532 people have browsed it

This article mainly introduces the method of deduplicating values ​​​​in JS and analyzes the operation skills of JS to deduplicate values ​​​​through array traversal, operation and other methods in the form of examples. Friends in need can refer to it

The example in this article describes how to implement array deduplication using JS. Share it with everyone for your reference, the details are as follows:

The running effect diagram is as follows:

Example of how to remove duplicate values ​​from an array using JS

The complete example code is as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript" language="javascript" >
Array.prototype.distinct = function(){
 var $ = this;
 var o1 = {}; //存放去重复值
 var o2 = {}; //存放重复值
 var o3 = []; //存放重复值
 var o; //数组单个变量
 for(var i=0;o = $[i];i++){
 if(o in o1){
  if(!(o in o2)) o2[o] = o;
  delete $[i];
 }else{
  o1[o] = o;
 }
 }
 $.length = 0; //清空原数组
 for(o in o1){
 $.push(o);
 }
 for(o in o2){
 o3.push(o);
 }
 return o3;
}
var a = [2,2,2,3,3,3,4,4,5,6,7,7];
console.log("原数组:" + a); //2,2,2,3,3,3,4,4,5,6,7,7
console.log("有重复的元素是:" + a.distinct()); //2,3,4,7
console.log("整理后的数组是:" + a);      //2,3,4,5,6,7
console.log("整理后的长度是:" + a.length)    //6
</script>
</head>
<body>
</body>
</html>
Copy after login

For more examples of JS methods to implement array deduplication, please pay attention to the PHP Chinese website for related articles!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template