-1

I am trying to sort some numbers in Javascript - this works fine, but I am trying to refactor some of the code so I am not hard coding field names. Below is my function:

data.sort(function(a, b) {
    return a.values[0].field1 - b.values[0].field1;
});

The problem is that I want to also use this same functionality with field2

I've tried doing something like the following (simplified):

var sortBy = "field1";

data.sort(function(a, b) {
    return a.values[0].sortBy- b.values[0].sortBy;
});

That is looking for a literal field name of sortBy though and is not working. Any help would be appreciated.

JamesE
  • 3,833
  • 9
  • 44
  • 82

1 Answers1

0
a.values[0].sortBy
a.values[0][sortBy]
Qwertiy
  • 19,681
  • 15
  • 61
  • 128
  • 1
    @tchelidze, [why?](/review/suggested-edits/11812565) – Qwertiy Mar 29 '16 at 12:44
  • Indeed, that suggested edit was worse than pointless. *In general*, though, code dump answers are not *useful* answers. Instead, say *what* you did, and (usually more importantly) *why*. – T.J. Crowder Mar 29 '16 at 12:45