I'm trying to sort a react state array which contains data from json file. The format of data in json is:
[
{
"name": "Rob Don",
"popularity": 84,
"id": "da6"
},
{
"name": "Henry Black",
"popularity": 34,
"id": "138"
},
{
"name": "Chris Smith",
"popularity": 56,
"id": "39c"
},...]
The code is below:
import React, { Component } from 'react';
import data from '../resources/myData.json';
class HOME extends Component {
constructor(props) {
super(props);
this.state = {
person: [...data.slice(0, 5)]
};
}
//SOME MORE CODE
I tried using the below logic but it doesn't work. I don't know why?
onSortChange = () => {
this.state.person.sort((a, b) =>
(a.name.toLowerCase() - b.name.toLowerCase())?-1:1
)
}
My question is how do I sort this.state.person
based on name?
CodePudding user response:
onSortChange = () => {
let person = [...this.state.person].sort((a, b) =>
(a.name.toLowerCase() - b.name.toLowerCase())?-1:1
)
this.setState({ person })
}
CodePudding user response:
You are missing the comparison operator (> 0
)
Try below
this.state.person.sort((a, b) =>
a.name.toLowerCase() - b.name.toLowerCase() > 0 ? -1 : 1
);
To set the output to the state, you need to use setState
method
onSortChange = () => {
this.setState((state) => {
if(Array.isArray(state.person)){
return {
person: state.person.sort((a, b) =>
a.name.toLowerCase() - b.name.toLowerCase() > 0 ? -1 : 1;
}
}
return state;
});
};