DEV Community

Discussion on: React: how to dynamically sort an array of objects using the dropdown (with React Hooks)

Collapse
 
ramonak profile image
Katsiaryna (Kate) Lupachova

Hi, Muyembell! Thank you for your feedback!
As for your question, you can sort array of objects by nested property this way (if you need to compare strings):

array.sort((a,b) => a.location.city.localeCompare(b.location.city));

Please, check the full updated code of the tutorial example with nested property sorting here - branch nested-sorting.

Collapse
 
muyembeii profile image
MuyembeII

Thank you 🙌. Worked like a charm

Collapse
 
encryptblockr profile image
encryptblockr

is it possible to have this sort as a component? so one can use on multiple pages? thanks

Thread Thread
 
ramonak profile image
Katsiaryna (Kate) Lupachova

yes, of course, it's totally possible. Just pass initial data and and sort type as a props to this component. The exact implementation depends on your use case.