1

This question is close to this one: Sort array of objects by string property value in JavaScript

However, the field value should be chosen by the user (saved in the sortBy parameter):

function sortList (sortBy, list) {
  return list.sort(function (val1, val2) {
    if (val1.sortBy > val2.sortBy) {

    return -1;
  }
  if (val1.sortBy < val2.sortBy) {
    return 1;
  }

  return 0;

  });
}

var myObj = [
  {a: 1, b: 3},
  {a: 3, b: 2},
  {a: 2, b: 40},
  {a: 4, b: 12}
];

sortList(myObj.a, myObj);

The object returns unchanged.

Community
  • 1
  • 1
Amir Rahbaran
  • 2,380
  • 2
  • 21
  • 28

1 Answers1

4

You're close:

function sortList (sortBy, list) {
  return list.sort(function (val1, val2) {
    if (val1[sortBy] > val2[sortBy]) {

    return -1;
  }
  if (val1[sortBy] < val2[sortBy]) {
    return 1;
  }

  return 0;

  });
}

var myObj = [
  {a: 1, b: 3},
  {a: 3, b: 2},
  {a: 2, b: 40},
  {a: 4, b: 12}
];

sortList("a", myObj);

If you want to access properties by some computed value, you use the [ ] operator instead of .. As it was, your code was always only looking for a property called "sortBy", and the passed-in parameter was ignored.

Pointy
  • 405,095
  • 59
  • 585
  • 614