1

Issue

Hello, Thanks ahead for anyone willing to help me, I have a problem with sorting an object array in js.

In this component I keep an array inside this.state of id, hours, day, and active.

My issue is when I try to sort the object.hours array the function won't sort by my logics and understanding of this comparator and the array stays same even if the sort expression is false.

Which can be found under sortHoursByTime declaration.

Expected Behavior

if (obj1.toTime < obj2.fromTime) then sort the array where obj1 is first in order.

Code:

export default class SetWorkingHours extends Component {

  constructor() {
    super();
    this.state = {
      workingDays: ['א׳', 'ב׳', 'ג׳', 'ד׳', 'ה׳', 'ו׳'].map((day, _id) => ({
        _id,
        name: day,
        hours: [],
        active: false,
      })),
      activeButton: -1,
    }
  }
  static defaultProps = {};

  sortHoursByTime(day) {
    let sortedDays = day;
    sortedDays.hours.sort((obj1,obj2) => obj1.fromTime < obj2.toTime);
    this.setState({workingDays: sortedDays});
  }

  appendWorkingHours = (hours) => {
    let dateHours = {
      fromTime: this.formatDateToHourString(new Date(hours.fromDate)),
      toTime: this.formatDateToHourString(new Date(hours.toDate))
    };
    let selectedWorkingDays = this.state.workingDays;
    selectedWorkingDays.forEach((day) => {
      if (day.active && this.isHoursValid(day, dateHours)) {
        day.hours.push(dateHours);
        this.sortHoursByTime(day)
      }
    });
    this.setState({workingDays: selectedWorkingDays})
  } // Editor's note: the closing curly brace of appendWorkingHours method 
    // was missing, so I added this line.
};

Environment

react-native -v: "0.54.2"

node -v: v9.8.0

npm -v: 5.6.0

yarn --version: 1.5.1

target platform: iOS

operating system: OSX

Community
  • 1
  • 1
S.Gal
  • 29
  • 4
  • 2
    The `.sort` comparator function should be returning a number, but yours returns a boolean. Try changing it to `(obj1,obj2) => obj1.fromTime - obj2.toTime`. – CRice Jul 26 '18 at 23:16

1 Answers1

2

When using Array.sort in JavaScript with a custom sorting function you need to return -1 less then, 0 equals, 1 greater then.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

This should fix your issue.

sortHoursByTime(day){
    let sortedDays = day;
    // Switch from < to -
    sortedDays.hours.sort((obj1,obj2) => obj1.fromTime - obj2.toTime); 
    this.setState({workingDays: sortedDays});
}
SudoKid
  • 439
  • 4
  • 14