Сортировка массива в Javascript - PullRequest
0 голосов
/ 12 июля 2020

Я создал функцию defineDataArray() для добавления данных в мой массив, и она заполняет массив tableData как двумерный массив значениями, взятыми из строк и ячеек тела веб-таблицы. Я прошел цикл с помощью for l oop и смог установить все переменные в массиве, но когда я вызываю свою функцию для сортировки, данные не могут быть добавлены в массив tableData и отсортированы. Мне нужно отсортировать массив tableData с помощью функции dataSort2D (). Функция dataSort2D () - это предварительно созданная функция, которая встроена и не подлежит изменению.

Это то, что у меня есть:

"use strict";

/*   
   Global Variables:
   tableData
      A 2-dimensional array of the data found in the body of the web table
      
   dataCategories
      An array of the column titles found the head of the web table
      
   sortIndex
      The index number of the column by which the web table should be
      sorted where 0 = 1st column, 1 = 2nd column, etc.
      
   sortDirection
      A value indicating direction of the sorting where a value of 1 sorts 
      the data in ascending order and a value of -1 sorts the data in descending order
    
   
   
   Functions List:   
   defineDataArray()
      Extracts values from the body of the web table and stores them in the
      tableData array
      
   writeTableData()
      Writes the sorted data into the table rows and cells       
      
   defineColumns()
      Extracts values form the column heads of the web table and stores 
      them in the dataCategories array; also sets up the onclick event
      handlers for the column heads so that the table can be sorted by
      clicking a table heading cell.
           
   columnSort(e)
      Event handler function that sorts the table data when a column
      heading is clicked  
   
   dataSort2D(a, b)
      Compare function used to sort numeric and alphabetical data from
      a 2-dimensional array 
*/

// define global variables
var tableData = [];
var dataCategories = [];
var sortIndex = 0;
var sortDirection = 1;

// create Event Listener
window.addEventListener("load", function()
  {
    defineDataArray();
    writeTableData();
    defineColumns();
  }
);

function defineDataArray() 
{
  var tableRows = document.querySelectorAll("table.sortable tbody tr");

  for(var i = 0; i<tableRows.length; i++)
  {
    var rowCells = tableRows[i].children;
    var rowValues = new Array(rowCells.length);
    for(var j = 0; j<rowCells.length; j++)
    {
        rowValues[j] = rowCells[j].textContent;
    }
    tableData[i] = rowValues;
  }
  tableData.sort(dataSort2D);
}

function dataSort2D(a, b) {
   if (isNaN(parseFloat(a[sortIndex])) === false) {
      return (a[sortIndex] - b[sortIndex])*sortDirection;
   } else {
      var astring = a[sortIndex].toLowerCase();
      var bstring = b[sortIndex].toLowerCase();
           
      if (bstring > astring) return -sortDirection;
      if (bstring < astring) return sortDirection;
      return 0;
   }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...