How can I get a set of unique years from a column containing full dates?

How can I get a set of unique years from a column containing full dates?

sport40lsport40l Posts: 3Questions: 2Answers: 0
edited August 2018 in Free community support

I am Moment.js to format the datetime in the first column of my datatable to include month, day, and year. I'm additionally trying to add a dropdown (select) filter at the top of my table that will sort by year. The code below pulls out all of the unique datetimes, but how can I get it so it pulls only the unique years?

$(document).ready(function() {
            $.fn.dataTable.moment( 'MMM DD, YYYY' );
            var table = $('#outreach').DataTable( {
                "order": [[0, "desc"]],
                "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
                "language": {
                    "zeroRecords": "No entries found. Please adjust your search parameters.",
                    "info": "Showing page _PAGE_ of _PAGES_",
                    "infoEmpty": "No entries found"
                },
                "stateSave": true,
                "stateDuration": 3600,
                "initComplete": function() {
                    this.api().columns([0]).every(function() {
                        var column = this;
                        var select = $("#outreach-year-filter");
                        column.data().unique().sort().each(function (d, j) {
                            console.log(d, j)
                            select.append('<option value="'+d+'">'+d+'</option>')
                        });
                    });
                }
            });

Answers

  • allanallan Posts: 63,455Questions: 1Answers: 10,465 Site admin

    map() is the way I'd do it. Use that to manipulate the data set to strip out everything other than the year and then unique() to reduce it to just unique values - e.g.:

    column
      .data()
      .map( function ( val ) {
        return val.split(', ')[1]; // assuming MMM DD, YYYY
      } )
      .unqiue()
      .sort()
      .each( function () {
        ...
      } );
    

    Allan

This discussion has been closed.