-1

I'm trying to sort an array of objects, but the property I'm sorting it by is not known beforehand. It's stored as a variable.

var items = [
    {foo: "4", bar: "5"},
    {foo: "7", bar: "1"},
    {foo: "5", bar: "9"},
];

var whatToSort = "";
if (Math.random() > .5) {
    whatToSort = "foo"
} else {
    whatToSort = "bar"
};

items.sort(function(a, b){
    return b.whatToSort - a.whatToSort;
};

This works if my sort() function returns b.bar - a.bar but not if the variable whatToSort is used. Is there a way to do this?

BDMayhem
  • 5
  • 2

1 Answers1

1

You need to use the square bracket notation:

return b[whatToSort] - a[whatToSort];

Otherwise, the JS engine thinks you are comparing properties that are literally named "whatToSort". This is one of the most common hangups people have when learning JavaScript. When you need to access a property of an object, but you are not sure what that property will be until runtime, you need to use the square bracket notation.

var myObject = {
  foo: 1,
  bar: 2
};
var myKey = 'foo';

myObject.foo;      // 1
myObject.bar;      // 2
myObject.myKey;    // undefined
myObject['foo'];   // 1
myObject['bar'];   // 2
myObject['myKey']; // undefined
myObject[myKey];   // 1
sbking
  • 7,630
  • 24
  • 33