0

Given an array;

const myArray = [
        {
            name : "Tom",
            age : 28,
            eyes : "brown"
        },
        {
            name : "Dave",
            age : 45,
            eyes : "green"
        },
        {
            name : "Harry",
            age : 22,
            eyes : "green"
        },
    ];

I know of the simple way to sort an array with the ternary operator

.sort((a, b) => a.age < b.age ? 1 : -1)

but I'm looking to make that age a variable key that I toggle with React useState so it would be more like;

.sort((a, b) => a.toggle < b.toggle ? 1 : -1);

const [toggle, setToggle] = useState('name');

But obviously putting the string 'name' in there won't work and just having name without quote marks returns that the variable does not exist. I've been racking my brain with how to say to JavaScript "use the JSON key, name, or age", not the string or a variable called name/age. Any help on this greatly appreciated!

Ash Hogarth
  • 497
  • 2
  • 6
  • 18
  • what is `toggle`? btw, only to values for sorting irritates the algorithm. – Nina Scholz Sep 19 '20 at 16:17
  • @AndrewLi I interpret as OP wants to change the key to sort. Not inital value is `"name"` – charlietfl Sep 19 '20 at 16:20
  • You need to use bracket notation like this: `a[toggle]`. Also, you need to return `0` from compareFunction when the values are same. – adiga Sep 19 '20 at 16:20
  • 1
    @charlietfl Ahhh, so the key itself is changing. If that's the case then this likely dupe? https://stackoverflow.com/q/4244896 – Andrew Li Sep 19 '20 at 16:22
  • @AndrewLi Ah yes, you are right. What's the process now? Do I delete the post or leave it up? I also want to make sure Nina and Dickens get the SO points they deserve – Ash Hogarth Sep 19 '20 at 16:28

3 Answers3

5

if useState is a function and let us say key is the variable for the function definition

Then a[key] will assume a.name in your case

if you pass "age" the a[key] will assume a.age in your case.

With your example, you may do something like this:

const [toggle, setToggle] = useState('name');
const sortedList = myArray.sort((a, b) => a[toggle] < b[toggle] ? 1 : -1);
kabirbaidhya
  • 3,264
  • 3
  • 34
  • 59
Dickens A S
  • 3,824
  • 2
  • 22
  • 45
3

You could hand over a variable for the property.

const sortBy = k => (a, b) => a[k] > b[k] || -(a[k] < b[k]);

array.sort(sortBy('age'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Use [] notation for variable object keys and check the type of the values to determine the sort comparison to use

const [toggle, setToggle] = useState('name');

const sortedList = myArray.sort((a, b) => {
   const aVal = a[toggle],
         bVal = b[toggle];
    
    if(typeof aVal === 'number'){
       return aVal - bVal;
    }
    return aVal.localeCompare(bVal)
});
kabirbaidhya
  • 3,264
  • 3
  • 34
  • 59
charlietfl
  • 170,828
  • 13
  • 121
  • 150