Currently, I am implementing React and facing a challenge with creating a reusable sorting component. This component is meant to sort an array of objects based on a specific property field. For instance, imagine having an array of objects with properties as follows:
let seed = [
{
name: 'John', age: '35', cars : '4', income: '35000'
},
{
name: 'Johnny', age: '15', cars : '0', income: '100'
},
{
name: 'Mary', age: '45', cars : '41', income: '350000'
},
]
To sort this array by the name
property, you can do so using the following code snippet:
let sortedData = [...seed].sort((a, b) => (a.name > b.name ? 1 : -1));
My goal is to create a function that allows for dynamic sorting based on any given field, something like this:
function sortData(array, field) {
array.sort((a, b) => (a.[field] > b.[field] ? 1 : -1))
}
However, it seems that the above syntax is not valid. Is there a way to achieve this without creating separate sorting functions for each individual property such as age
, cars
, income
, etcetera?