简体   繁体   中英

How to sort by date and then by time using Javascript

I have written a script to help me convert a very long and tedious task of copying numbers from a paragraph and retyping them into a table.

However, I need to be able to sort these "paragraphs" by date, and then within each date, they have to be sorted by time (I know 3333Z is not a valid time, this is only for testing and to make sure it sorts correctly).

This is how it needs to display as the final product. My code builds a CSV version of this table, that I paste into Excel to get the table.

March 4
--------------------------------------------------------------------------------------
|  Value 1    |  Value 2    |  Value 3    |  Value 4     |   Value 3    |  Value 6   |
--------------------------------------------------------------------------------------
|     1111Z   |     1111Z   |   12345.67  |  123456.123  |    123.123   |   456.78   |
--------------------------------------------------------------------------------------
|     2222Z   |     2222Z   |   12345.67  |  123456.123  |    123.123   |   456.78   |
--------------------------------------------------------------------------------------
|     3333Z   |     3333Z   |   12345.67  |  123456.123  |    123.123   |   456.78   |
--------------------------------------------------------------------------------------

March 12
--------------------------------------------------------------------------------------
|  Value 1    |  Value 2    |  Value 3    |  Value 4     |   Value 3    |  Value 6   |
--------------------------------------------------------------------------------------
|     1111Z   |     1111Z   |   12345.67  |  123456.123  |    123.123   |   456.78   |
--------------------------------------------------------------------------------------
|     2222Z   |     2222Z   |   12345.67  |  123456.123  |    123.123   |   456.78   |
--------------------------------------------------------------------------------------
|     3333Z   |     3333Z   |   12345.67  |  123456.123  |    123.123   |   456.78   |
--------------------------------------------------------------------------------------

March 29
--------------------------------------------------------------------------------------
|   Value 1   |  Value 2    |  Value 3    |  Value 4     |   Value 3    |  Value 6   |
--------------------------------------------------------------------------------------
|     1111Z   |     1111Z   |   12345.67  |  123456.123  |    123.123   |   456.78   |
--------------------------------------------------------------------------------------
|     2222Z   |     2222Z   |   12345.67  |  123456.123  |    123.123   |   456.78   |
--------------------------------------------------------------------------------------
|     3333Z   |     3333Z   |   12345.67  |  123456.123  |    123.123   |   456.78   |
--------------------------------------------------------------------------------------

I have a value called line1field2 that has the date and time in the format of DDHHHHZ. In the example above, DD would give 4, 12, and 29. Then is must sort by the time (HHHH) to create the table part.

I know this can be completed in other languages, but, due to system requirements, this must be in plain JavaScript, no libraries like jQuery, and it must work with FireFox 3.6.3.

This code below works, except it does not separate by date.

Also, I would like to save this as CSV file (or a file that will keep the table format) as a final output, I know I could do with PHP, but I don't think I can do this with JavaScript. If anyone knows of a way that this can be done, please let me know.

If I was unclear on anything, please ask and I will try to explain it better.

Thanks

    <!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>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Converter</title>
    <style type="text/css">
    body {
        background: #C8C8C8;
        margin: 10px;
        font-size: 100%;
    }

    .floatstop {
        clear: both;
    }

    .hidden {
        display: none;
    }

    .unhidden {
        display: block;
    }

    #button {
        margin: 0px auto;
    }

    #instruction {
        margin: 5px;
        width: 500px;
    }

    #workspace {
        background: #FFFFFF;
        float: left;
        margin: 0px auto;
        height: 300px;
        width: 505px;    
        border-style: ridge;
        border-width: 5px;
        border-color: gray;
    }

#outer {
    background: #F0F0F0;
    width: 1035px;
    margin: 0px auto;
    padding: 10px;
    border-style: solid;
    border-width: 3px;
    border-color: black;
}

#preview {
    background:   #FFFFFF;
    float: right;
    margin: 0px auto;
    height: 300px;
    width: 505px;
    border-style: ridge;
    border-width: 5px;
    border-color: gray;
}

#viewCSV {
    width: 500px;    
}

#viewHTML {
    width: 500px;
}
</style>
</head>
<body>
<script type="text/javascript" language="JavaScript">

//Select text function in Preview textarea
function selectText(id) {
    document.getElementById(id).focus();
    document.getElementById(id).select();
}

//Trim leading zeros    
function trimNumber(s) {
    while (s.substr(0, 1) == '0' && s.length > 1) { s = s.substr(1, 9999); }
    return s;
}

//Trim leading zeros, but leave two digits before decimal point
function trimNumber2(s) {
    while (s.substr(0, 2) == '00' && s.length > 1) { s = s.substr(1, 9999); }
    return s;
}

var row = [];
var results = [];

function conversionCode() {
    var pastedText = document.getElementById("pastedText").value; //get text from input
    var para = pastedText.split("\n\n");
    var i = 0;
    for (i = 0; i < para.length; i++) { //start conversion loop
        var report = para[i];

        //Arrays are zero-based.
        var splitLines     = report.split('//');
        var line1Arr       = splitLines[0];
        var line2Arr       = splitLines[1];
        var line3Arr       = splitLines[2];
        var line4Arr       = splitLines[3];
        var line5Arr       = splitLines[4];

        //Break out FIRST line.
        var lineAAA        = splitLines[0].split('/');
        var datasetName1   = lineAAA[0];
        var line1field1    = lineAAA[1];
        var line1field2    = lineAAA[2];
        var line1field3    = lineAAA[3];
        var line1field4    = lineAAA[4];
        var line1field5    = lineAAA[5];
        var line1field6    = lineAAA[6];
        var line1field7    = lineAAA[7];
        var line1field8    = lineAAA[8];
        var line1field9    = lineAAA[9];

        //Break out SECOND line.
        var lineBBBBB      = splitLines[1].split('/');
        var datasetName2   = lineBBBBB[0];
        var line2field1    = lineBBBBB[1];
        var line2field2    = lineBBBBB[2];
        var line2field3    = lineBBBBB[3];
        var line2field4    = lineBBBBB[4];
        var line2field5    = lineBBBBB[5];
        var line2field6    = lineBBBBB[6];
        var line2field7    = lineBBBBB[7];

        //Break out THIRD line.
        var lineCCC        = splitLines[2].split('/');
        var dataSetName3   = lineCCC[0];
        var line3field1    = lineCCC[1];
        var line3field2    = lineCCC[2];
        var line3field3    = lineCCC[3];
        var line3field4    = lineCCC[4];
        var line3field5    = lineCCC[5];

        //Break out FOURTH line.
        var lineDDDD1      = splitLines[3].split('/');
        var dataSetName4   = lineDDDD1[0];
        var line4field1    = lineDDDD1[1];
        var line4field2    = lineDDDD1[2];
        var line4field3    = lineDDDD1[3];
        var line4field4    = lineDDDD1[4];
        var line4field5    = lineDDDD1[5];
        var line4field6    = lineDDDD1[6];
        var line4field7    = lineDDDD1[7];

        //Break out FIFTH line.
        var lineDDDD2      = splitLines[4].split('/');
        var dataSetName5   = lineDDDD2[0];
        var line5field1    = lineDDDD2[1];
        var line5field2    = lineDDDD2[2];
        var line5field3    = lineDDDD2[3];
        var line5field4    = lineDDDD2[4];
        var line5field5    = lineDDDD2[5];
        var line5field6    = lineDDDD2[6];
        var line5field7    = lineDDDD2[7];

        //Change variables to correct formating
        //date - selecting and validating the date from line1field2
        var date = line1field2.slice(0, -5);
        var min = 1;
        var max = 31;
        var num = parseInt(date);
        if (min > num || max < num) {
            alert('Invalid date');
            exit();
        }

        //Time - Correcting format
        line1field2 = line1field2.slice(2);
        line1field3 = line1field3.slice(2);

        //line3field1 - remove letters from end of field, remove leading zeros
        line3field1 = line3field1.slice(0, -3);
        line3field1 = trimNumber(line3field1);

        //line3field3 - Split field on ':'
        line3field3 = line3field3.split(':');
        line3field3 = line3field3[1];

        //line4field1 - Split field on ':', and removing leading zeros
        line4field1 = line4field1.split(':');
        line4field1 = line4field1[1];
        line4field1 = trimNumber(line4field1);

        //line3field5 - Remove leading zeros, but keep at least two numbers before the
        //decimal point (Example: 01.123)
        line3field5 = line3field5.split(':');
        line3field5 = line3field5[1];
        line3field5 = trimNumber2(line3field5);

        //Create Array for each row in table.
        row[row.length] = line1field2;
        row[row.length] = line1field3;
        row[row.length] = line3field1;
        row[row.length] = line3field3;
        row[row.length] = line4field1;
        row[row.length] = line3field5;

        //Add each report's data to array'
        results.push(row);

        //Remove data from row for next loop 
        row = [];

    }

    //Sort results array for display
    results = results.sort();

    //Build HTML table

    //Build CSV text  
    resultsHeader = "Value 1,Value 2,Value 3,Value 4,Value 5,Value 6" + "\n";
    document.getElementById("plainOutput").innerHTML = resultsHeader;

    for (i = 0; i < results.length; i++) {
        document.getElementById("plainOutput").innerHTML += results[i] + "\n";
    }

};

</script>

<div id="outer">
    <h1 align="center">CONVERTER</h1>
    <div id="workspace">
    <h2 align="center">Workspace</h2>      
    <form action="" method="get" id="inputForm">
    <textarea id="pastedText" style="width:500px" rows="10"></textarea>
        <div id="button" class="floatstop">
        <p><input type="button" value="Convert" onclick="conversionCode ()"></p>    
        </div>
    </form>
    </div>
    <div id="preview">
    <h2 align="center">Preview</h2>
        <div id="viewCSV"> 
        <form action="" method="get" name="csvDisplay">  
        <textarea id="plainOutput" style="width: 500px" rows="10" readonly="readonly" onClick="selectText('plainOutput')"></textarea>
        <p><input type="button" value="Select Text" onClick="selectText('plainOutput')"/></p>
        </form>
        </div>
    </div>
    <div id="instruction" > 
    <p style="margin-left: 20px"><strong>Instructions:</strong></br>
    <ol>
        <li>Paste text into the Workspace.</li>
        <li>Click the "Convert" button.</li>
        <li>Cclick on the text or the Select button at the bottom to select 
            the text.</li>
        <li>You <strong>must</strong> copy the text by either Right-clicking 
            and choose Copy or by pressing Control+C.</li>
        <li>Paste the text into Excel as CSV.</li>
        <li>Format table as necessary.</li>
        <li>Select table and paste into product.</li>
    </ol>
    </div>
</div>
</body>
</html>

Convert the "times" to Date() objects (split the string, convert into numbers, feed the constructor).

Then use the sort() method of your dates-array. Using a custom compareFunction, you can easily sort dates. Have a look at the number compare function in the linked docs: It will also work for Date objects because the will be implicitly converted into numbers.

After that, you will be able to split the array up into subarrays for each date.

export const sortByDate = (array, direction) => {
      if (!array.length) return []
      if (direction.toLowerCase() === "asc") {
        return array.sort(
          (a, b) => new Date(a).getTime() - new Date(b).getTime()
        )
      }
      if (direction.toLowerCase() === "desc") {
        return array.sort(
          (a, b) =>
            new Date(String(b)).getTime() -
            new Date(String(a)).getTime()
        )
      }
      return array
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM