javascript tips - assign uniqueness to elements

It is a common practice to make sure that each element of an array or an collection should be unqiue, application scenario including in the divide and conquer step, you may want to merge some array from different sub-step but you want to make sure no duplicate ends up in the list. 

 

below shows the code and test code to show you a common technique to make that happen.

 

<!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>
    <title></title>
    <script type="text/javascript" src="../unit.js"></script>
    <style type="text/css">
      #results li.pass {color:Green}
      #results li.fail {color:Red}
    </style>
</head>
<body>
<div id="test">
  <b>Hello</b>, I'm a ninja
</div>
<div id="test2"></div>
<script type="text/javascript">

  (function () {
    var run = 0;
    this.unique = function (array) {
      var ret = [];
      run++;
      for (var i = 0, length = array.length; i < length; i++) {
        var elem = array[i];

        if (elem.uniqueID !== run) {
          elem.uniqueID = run;
          ret.push(array[i]);
        }
      }
      return ret;
    };
  })();

  window.onload = function () {
    test("Test filter uniqueness", function () {
      var divs2 = document.getElementsByTagName("div");
      var divs = unique(document.getElementsByTagName("div"));
      assert(divs.length === 2, "No duplicates removed.");

      var body = unique([document.body, document.body]);
      assert(body.length === 1, "Body duplicate removed.");
    });
  };
</script>

<ul id="results"></ul>
</body>
</html>
 

the solution is basically assign some property to an element, and check if the new testing element has the matching unique id, if not, reassign the uniqueID; and the key is function will use a different ID each time the method to remove duplicate is called. 

你可能感兴趣的:(JavaScript)