Home > Web Front-end > JS Tutorial > Example tutorial on finding duplicate elements in js array

Example tutorial on finding duplicate elements in js array

零下一度
Release: 2017-06-16 09:19:54
Original
1805 people have browsed it

This article mainly introduces the JS method of finding repeated elements in an array, and compares and analyzes JavaScript's traversal, judgment, sorting and other related operation skills for arrays based on specific examples. Friends in need can refer to it

The example in this article describes the method of finding duplicate elements in an array using JS. Share it with everyone for your reference, the details are as follows:

The data type of JS has an array. Today we will talk about a kind of processing of arrays. I believe many people have encountered finding unique elements from an array, but what I encountered was finding duplicate elements from an array.

There are many ways to find non-repeating elements from a js array. Here is one:


<!DOCTYPE html>
<html>
<body>
<script>
Array.prototype.deleteEle=function(){
  var newArr = this;
  for (var i=newArr.length-1; i>=0; i--)
  {
    var targetNode = newArr[i];
    for (var j=0; j<i; j++)
    {
      if(targetNode == newArr[j]){
        newArr.splice(i,1);
        break;
      }
    }
  }
  return newArr;
}
var arr = ["a","b","c","c","ab","d","ab","d","c"];
console.log(arr.deleteEle());
</script>
</body>
</html>
Copy after login

The running effect is as follows:

Here is another way to find duplicate elements from a js array:


<!DOCTYPE html>
<html>
<body>
<script>
var a = [5,4,3,2,1,2,3,2,1,];
Array.prototype.duplicate=function() {
  var tmp = [];
  this.concat().sort().sort(function(a,b){
    if(a==b && tmp.indexOf(a) === -1) tmp.push(a);
  });
  return tmp;
}
console.log(a.duplicate())
</script>
</body>
</html>
Copy after login

Running renderings as follows:

The above is the detailed content of Example tutorial on finding duplicate elements in js array. For more information, please follow other related articles on the PHP Chinese website!

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