0

I need to use JavaScript to sort this sample data by either storeID number or the number of transactions:

transactionList = [
  {storeID: 102, transactions: 6},
  {storeID: 64, transactions: 22},
  {storeID: 295, transactions: 9},
  {storeID: 83, transactions: 4},
  {storeID: 96, transactions: 14}
];

Here is the function I was trying to build, where sort modifier is either "storeID" or "transactions":

function sortTransactions (modifier, transactionList) {
  return transactionList.sort(function(x, y) { 
    return x.modifier - y.modifier;
  });
}

So if I run this in console:

sortTransactions("storeID", transactionList);

I expected that my transactionList would be sorted. But the function just returns the initial value.

When I injected console.log(x.modifier, y.modifier) into the mix, it shows a value of undefined, so clearly I'm doing one or more things wrong here.

I had searched and found this to be the essence of what I was going for, but couldn't seem to translate that into my own working function: Javascript object list sorting by object property

Any help is very much appreciated!

Community
  • 1
  • 1
  • 3
    Problem here `x.modifier != x[modifier]` – elclanrs Jul 22 '14 at 22:27
  • Write a good sort function: 1) data type, the result is different when you sort by number or string, for example, is 18>123 ? how about date sorting? 2)Usually I put a switch for desc or ascending. – John Jin Jul 22 '14 at 22:53

1 Answers1

1

As pointed out in comment, if you want to access a property named 'id' of an object, you can do it in two ways:

object.id
object['id']

if the name of the property is stored inside a string though, you have to access like this

var modifier = 'id';
object[modifier]
lelloman
  • 13,883
  • 5
  • 63
  • 85