I need to create a function for sorting an array of objects. Array looks something like this:
array=[ 0: {id: "7", name: "Aaaaa", level: "3/4", generation: "2", area: "JavaScript", …} 1: {id: "6", name: "Bbbbbb", level: "2/4", generation: "2", area: "JavaScript", …} 2: {id: "10", name: "DEV #1", level: "1/1", generation: "1", area: "Development", …} ]
this is how i call the function
sortHandle={() => this.sortArray("someProperty", "desc/asc")}
i've managed to make it work but only after i click on sorter the second time.
sortCourses(sorter, asc) {
let courses = this.state.courses;
let sortedCourses = []
switch (sorter) {
case 'level':
sortedCourses.push(courses.sort((a, b) => { return (parseInt(a.level) - parseInt(b.level)) ? 1 : -1 }))
break;
case 'generation':
sortedCourses.push(courses.sort((a, b) => { return (parseInt(a.generation) - parseInt(b.generation)) ? 1 : -1 }))
break;
case 'name':
sortedCourses.push(courses.sort((a, b) => { return (a.name.toLowerCase() - b.name.toLowerCase()) ? 1 : -1 }))
case 'area':
sortedCourses.push(courses.sort((a, b) => { return (a.area.toLowerCase() - b.area.toLowerCase()) ? 1 : -1 }))
break;
case 'date':
sortedCourses.push(courses.sort((a, b) => { return (a.startDate - b.startDate) ? 1 : -1 }))
break;
}
this.setState({ courses: sortedCourses[0] }, () => { console.log(this.state.courses) })
if (asc) {
return sortedCourses[0]
}
else if (!asc) {
return sortedCourses[0].reverse()
}
}
I get sortProperty and asc/desc from props sortHandle which is a function in child component.
sortHandle={(sorter,asc) => this.sortCourses(sorter,asc)}
and in my child component sorters look like this:
<span className="margin-h-10 row align-center padding-r-5 pointer"
onClick={() => {
this.setState({ asc: !this.state.asc });
this.props.sortHandle('name', this.state.asc)
}}>
<span className="margin-r-5">Name</span>
<FontAwesomeIcon
icon={this.state.asc ? 'chevron-up' : 'chevron-down'}
style={{ color: "#7f7f7f", fontSize: "10px" }}
/>
</span>
<span className="margin-h-10 row align-center padding-r-5 pointer"
onClick={() => {
this.setState({ asc: !this.state.asc });
this.props.sortHandle('date', this.state.asc)
}}>
<span className="margin-r-5">Date</span>
This seems to work fine but only after i click sorter 2 times. I guess it has something to do with state. Any solutions?
this.setState([...array].sort(...))