Home > Software design >  How to select item without repetition in JavaScript
How to select item without repetition in JavaScript

Time:10-05

I have a website script that will read user uploaded csv file and show it on a html table.

When user upload their csv file, my script will automatic add a new column named Device and distribute a list item to the existing csv record.

For example, if user uploaded csv that contain 4 records, the Device column will add three serial code based on this list:

var filterserial = ['K4Z7-9RFL-XCXS', 'TEIK-YMJF-4QQG', '4SB9-NR2D-742E', 'TY83-FPSX-C3WS', 'YVLM-W2T1-YNSI']

Example:

enter image description here

PROBLEM : When there are multiple attempt to upload the csv file, there is a chance that the device serial will be duplicated. Since all the device serial should be unique for each ID, how can i prevent the device serial to be duplicated? Thanks in advance For example :

enter image description here

Full Code (HTML & JAVSCRIPT):

<!DOCTYPE HTML>
<html>

<head>


  <script type="text/javascript" src="https://unpkg.com/[email protected]/dist/xlsx.full.min.js"></script>
</head>

<body>
  <div class="container">
    <h2 class="text-center mt-4 mb-4">Convert Excel to HTML Table using JavaScript</h2>
    <div class="card">
      <div class="card-header"><b>Select Excel File</b></div>
      <div class="card-body">

        <input type="file" id="excel_file" />

      </div>
    </div>
    <div id="excel_data" class="mt-5"></div>
  </div>
</body>

</html>

<script>
  const excel_file = document.getElementById('excel_file');

function randomNoRepeats(array) {
  var copy = array.slice(0);
  return function() {
    if (copy.length < 1) { copy = array.slice(0); }
    var index = Math.floor(Math.random() * copy.length);
    var item = copy[index];
    copy.splice(index, 1);
    return item;
  };
}

var filterserial = ['K4Z7-9RFL-XCXS', 'TEIK-YMJF-4QQG', '4SB9-NR2D-742E', 'TY83-FPSX-C3WS', 'YVLM-W2T1-YNSI']
var chooser = randomNoRepeats(filterserial);


  excel_file.addEventListener('change', (event) => {

    if (!['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel'].includes(event.target.files[0].type)) {
      document.getElementById('excel_data').innerHTML = '<div class="alert alert-danger">Only .xlsx or .xls file format are allowed</div>';

      excel_file.value = '';

      return false;
    }

    var reader = new FileReader();

    reader.readAsArrayBuffer(event.target.files[0]);

    reader.onload = function(event) {

      var data = new Uint8Array(reader.result);

      var work_book = XLSX.read(data, {
        type: 'array'
      });

      var sheet_name = work_book.SheetNames;

      var sheet_data = XLSX.utils.sheet_to_json(work_book.Sheets[sheet_name[0]], {
        header: 1
      });

      if (sheet_data.length > 0) {
        var table_output = '<table class="table table-striped table-bordered">';

        for (var row = 0; row < sheet_data.length; row  ) {

          table_output  = '<tr>';
          if (row == 0) {
            table_output  = '<th>'   ['Device']   '</th>'
          } else {
                                table_output  = '<td>'   [chooser()]   '</td>'

          }

          for (var cell = 0; cell < sheet_data[row].length; cell  ) {

            if (row == 0) {

              table_output  = '<th>'   sheet_data[row][cell]   '</th>';

            } else {

              table_output  = '<td>'   sheet_data[row][cell]   '</td>';

            }

          }

          table_output  = '</tr>';

        }

        table_output  = '</table>';

        document.getElementById('excel_data').innerHTML = table_output;
      }

      excel_file.value = '';

    }

  });
</script>

CodePudding user response:

How about moving the chooser initialization inside the change listener an defining it this way?

var shuffledSerials = filterserial.slice(0).sort(() => return 0.5 - Math.random() );
var chooser = () => shuffledSerials.pop();

This way the serials get shuffled every time a new file is loaded and the chooser just pops items out from the newly created array.

<!DOCTYPE HTML>
<html>

<head>


  <script type="text/javascript" src="https://unpkg.com/[email protected]/dist/xlsx.full.min.js"></script>
</head>

<body>
  <div class="container">
    <h2 class="text-center mt-4 mb-4">Convert Excel to HTML Table using JavaScript</h2>
    <div class="card">
      <div class="card-header"><b>Select Excel File</b></div>
      <div class="card-body">

        <input type="file" id="excel_file" />

      </div>
    </div>
    <div id="excel_data" class="mt-5"></div>
  </div>
</body>

</html>

<script>
  const excel_file = document.getElementById('excel_file');

  var filterserial = ['K4Z7-9RFL-XCXS', 'TEIK-YMJF-4QQG', '4SB9-NR2D-742E', 'TY83-FPSX-C3WS', 'YVLM-W2T1-YNSI'];


  excel_file.addEventListener('change', (event) => {

    if (!['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel'].includes(event.target.files[0].type)) {
      document.getElementById('excel_data').innerHTML = '<div class="alert alert-danger">Only .xlsx or .xls file format are allowed</div>';

      excel_file.value = '';

      return false;
    }

        var shuffledSerials = filterserial.slice(0).sort(() => 0.5 - Math.random() );
        var chooser = () => shuffledSerials.pop();

    var reader = new FileReader();

    reader.readAsArrayBuffer(event.target.files[0]);

    reader.onload = function(event) {

      var data = new Uint8Array(reader.result);

      var work_book = XLSX.read(data, {
        type: 'array'
      });

      var sheet_name = work_book.SheetNames;

      var sheet_data = XLSX.utils.sheet_to_json(work_book.Sheets[sheet_name[0]], {
        header: 1
      });

      if (sheet_data.length > 0) {
        var table_output = '<table class="table table-striped table-bordered">';

        for (var row = 0; row < sheet_data.length; row  ) {

          table_output  = '<tr>';
          if (row == 0) {
            table_output  = '<th>'   ['Device']   '</th>'
          } else {
                                table_output  = '<td>'   [chooser()]   '</td>'

          }

          for (var cell = 0; cell < sheet_data[row].length; cell  ) {

            if (row == 0) {

              table_output  = '<th>'   sheet_data[row][cell]   '</th>';

            } else {

              table_output  = '<td>'   sheet_data[row][cell]   '</td>';

            }

          }

          table_output  = '</tr>';

        }

        table_output  = '</table>';

        document.getElementById('excel_data').innerHTML = table_output;
      }

      excel_file.value = '';

    }

  });
</script>

  • Related