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