I am making an app using React.js and firebase where users can enter the name, and the person's address.
The object in firebase looks like this:
L1NSTjqA10Qc85d7Kcc
- name: John Doe,
- address: 1 Maple Ave
I have printed the name, and address successfully onto the DOM, but i would like to sort it alphabetically, by the name.
So my list would look like this for example:
Jane Doe - 34 Green Street
John Doe - 1 Maple Ave
Riley Smith - 3 Happy Street
Here is my JSX so far, for when mapping over the array of objects, on the parent component:
<ul>
{this.state.contacts.map((res)=> <List data={res}/>)}
</ul>
and just in case, here is my componentDidMount:
componentDidMount() {
const dbRef = firebase.database().ref();
dbRef.on("value", (firebaseData) => {
const itemsArray = [];
const itemsData = firebaseData.val();
for (let itemKey in itemsData) {
itemsArray.push(itemsData[itemKey])
}
this.setState({ contacts: itemsArray})
})
}
I have tried to do the following, from another stack overflow forum, however it did not work:
const myData = [].concat(this.state.contacts)
.sort((a,b)=> a.name > b.name
.map((res)=> <List data={res}/>);
To sort an array of objects in React:Create a shallow copy of the array. Call the sort() method on the array passing it a function. The function is used to define the sort order.
We can do this in JavaScript by using the sort() method directly or with the compare function. In case you are in a rush, here are the two ways: // order an array of names names. sort(); // order an array of objects with name users.
To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.
Sorting A-Z This is quite simple and the sort() function will automatically sort and array of strings A-Z. No other parameter is required in this case.
The logic part where you are trying to sort and then map can be done like this.
const myData = this.state.contacts
.sort(function(a, b) {
if(a.name.toLowerCase() < b.name.toLowerCase()) return -1;
if(a.name.toLowerCase() > b.name.toLowerCase()) return 1;
return 0;
})
.map((item, i) => <List key={i} data={item} />);
Or if you want to do it even shorter you can do it like this.
const myData = this.state.contacts
.sort((a, b) => a.name.localeCompare(b.name))
.map((item, i) => <List key={i} data={item} />);
localeCompare
function is a method of String
In your method called
dbRef.on("value", (firebaseData) => {
this.setState({
contacts: Array.from(firebaseData.val()).sort((a, b) => a.name.localeCompare(b.name))})
});
}
In your render
method do the following
render () {
return (
<ul>
{
this.state.contacts.map((item, i) => <List key={i} data={item} />)
}
</ul>
);
}
Does this help?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With