1

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
1
  • 2
    You are using wrong syntax. instead of a.[field] use a[field]. Commented Jul 22, 2019 at 5:20

1 Answer 1

1

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; }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.