Kaleidics
Kaleidics

Reputation: 177

JavaScript: How do I pass a string argument to a function to use to sort an array of objects by the value of that string argument?

I am also working in React. I am trying to build a reusable sorting component, which sorts an array of objects by a property field. For example with an array of objects with properties like so:

let seed = [
    {
        name: 'John', age: '35', cars : '4', income: '35000'
   },
   {
        name: 'Johnnny', age: '15', cars : '0', income: '100'
   },
    {
        name: 'Mary', age: '45', cars : '41', income: '350000'
   },
]

I can write it like this to sort the array by the name property:

let sortedData = [...seed].sort((a, b) => (a.name > b.name ? 1 : -1));

What I would like to do is something like this:

function sortData(array, field) {
  array.sort((a, b) => (a.[field] > b.[field] ? 1 : -1))
}

But it doesn't look like this is valid syntax. How can I do this without writing a different sort of each property like:

let sortedData = [...seed].sort((a, b) => (a.age > b.age ? 1 : -1));

cars
income
and so on

Upvotes: 1

Views: 140

Answers (1)

Jack Bashford
Jack Bashford

Reputation: 44087

Remove the dot from your accessor. You can use either bracket notation or dot notation for each key, not both.

let seed = [
    {
        name: 'John', age: '35', cars : '4', income: '35000'
   },
   {
        name: 'Johnnny', age: '15', cars : '0', income: '100'
   },
    {
        name: 'Mary', age: '45', cars : '41', income: '350000'
   },
]

function sortData(array, field) {
  return array.sort((a, b) => (a[field] > b[field] ? 1 : -1))
}

let sortedData = sortData([...seed], "cars");

console.log(sortedData);
.as-console-wrapper { max-height: 100% !important; top: auto; }

Upvotes: 1

Related Questions