Search code examples
javascriptreactjssortingimmutable.jsvirtual-table

Sorting By Asc and Desc date


trying to sort my immutable list by desc and or asc by a date give, but its not really working exactly, on sorting for words it works fine but not the following Date that are in the list . Using the descending and ascending value from react virtualized. Would be helpful if someone could tell me how to best go about this. Or if not, what are other alternatives?

import { List } from 'immutable';
import * as React from 'react';
import { SortDirection } from 'react-virtualized';


class TopComp extends React.Component {
  constructor(props) {
    super(props);
    const data = List([
      {
        0: {
          'Date Reported': 'Mar 16, 2015',
        }
      },
      {
        0: {
          'Date Reported': 'Mar 16, 2015',
        }
      },
      {
        0: {
          'Date Reported': 'Mar 02, 2015',
        }
      },
      {
        0: {
          'Date Reported': 'Mar 02, 2015',
        }
      },
      {
        0: {
          'Date Reported': 'Feb 23, 2015',
        }
      },
      {
        0: {
          'Date Reported': 'Feb 23, 2015',
        }
      },
      {
        0: {
          'Date Reported': 'Oct 07, 2014',
        }
      },
      {
        0: {
          'Date Reported': 'May 30, 2014',
        }
      },
    ]);

    this.state = {
      data,
    };
  }


  render() {
    const { data } = this.state;
    let t = null;
    t = data.sortBy(item => item[0]['Date Reported']).update((t) => {
      console.log(t);
      const Direction = SortDirection.DESC;
      return (Direction === SortDirection.DESC ? t.reverse() : t);
    });
    console.log(t.toJS());

    return (
      <div>
        <span>Hey</span>
      </div>
    );
  }
}


export default TopComp;

Don't really see why some dates come as they should ?


Solution

  • Your dates don't sort properly because the most significant part (the year) is at the end of the string, and the sort will treat them as the least significant, hence your problem.

    If you can get the data in a different way (I'm hoping you can), add another element to the data, which can either be a timestamp or an ISO date string, which will sort properly.

    const data = List([
      {
        0: {
          'Date Reported': 'Mar 16, 2015',
          'isodate': "2015-03-16T03:30:49.566+0000"
        }
      },