JS implements a method to find duplicate lines for a sorted string

  • 2021-01-14 05:41:41
  • OfStack

This article shows the JS implementation of finding duplicate rows for sorted strings. To share with you for your reference, as follows:

To implement such a requirement, there are many lines of 10-digit numbers in an Editplus document that are already sorted.

Such as:

1234567890
1234567891
1234567892
1234534124
1234614124
4321412414
5636373573

Is there any easy way to find two rows with at least the first seven digits in common?

For example, in the numbers above, you can find

1234567890
1234567891
1234567892


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
  <title></title>
  <style type="text/css">
    div{ float:left; }
    #divCenter{ padding-top:100px;margin:0 50px; }
    .txt{width:200px;height:200px;}
    #txtOldData{background-color:#A6CAF0;}
    #txtAnswer{background-color:#EBA9A6;}
  </style>
  <script type="text/javascript">
    function test() {
      var arr = document.getElementById("txtOldData").value.replace(/ +/g, '').split("\n");
      var tempStr = arr[0].substring(0, 7);
      var compareLen = 7, equalNum = 0;
      var answer = "";
      for (var i = 1; i < arr.length; i++) {
        if (arr[i].substring(0, 7) == tempStr) {
          if (equalNum == 0)
            answer += arr[i - 1] + "\n";
          answer += arr[i] + "\n";
          equalNum++;
        } else {
          tempStr = arr[i].substring(0, 7);
          equalNum = 0;
        }
      }
      document.getElementById("txtAnswer").value = (answer);
    }
  </script>
</head>
<body>
  <div>
     Please enter the value: <br />
    <textarea id="txtOldData" class="txt">
1234567890
1234567891
1234567892
1234534124
1234614124
4321412414
5636373573
    </textarea>
  </div>
  <div style="padding-top:90px;padding" >
    <input type="button" value=" test ==>" onclick="test()" />
  </div>
  <div>
     Results: <br />
    <textarea id="txtAnswer" class="txt"></textarea>
  </div>
</body>
</html>

More about JavaScript related content interested readers can view the site special topic: "JavaScript search algorithm skills summary", "JavaScript animation effects and skills summary", "JavaScript error and debugging skills summary", "JavaScript data structure and algorithm skills summary", "JavaScript eraser algorithm and skills summary" and "JavaScript mathematical operation usage summary"

I hope this article described to everyone JavaScript programming help.


Related articles: