2

I am creating an individual function for every key in the object like this:

Object

let users = [
  { name: "John", age: 20, surname: "Johnson" },
  { name: "Pete", age: 18, surname: "Peterson" },
  { name: "Ann", age: 19, surname: "Hathaway" }
];

Simple sorting function

// Sorting by name (Ann, John, Pete)
users.sort((a, b) => a.name > b.name ? 1 : -1);

// Sorting by age (Pete, Ann, John)
users.sort((a, b) => a.age > b.age ? 1 : -1);

It works well, but I need to create a dynamic function with closure, which will be called like this:

users.sort(byField('name')); instead of users.sort((a, b) => a.name > b.name ? 1 : -1);

So far I tried this:

function byField(str) {
  return (a, b) => a.str > b.str ? 1 : -1;
}

console.table(users.sort(byField('name')));
console.table(users.sort(byField('age')));

But it just returns the unsorted object.

Robert Hovhannisyan
  • 2,938
  • 6
  • 21
  • 43

1 Answers1

1

You need a property accessor with brackets and a function which works kind of symmetrically and respects same values.

Read some more about functions which returns only a part, like -1 and 1 or just a boolean value: Sorting in JavaScript: Shouldn't returning a boolean be enough for a comparison function?

const withKey = key => (a, b) => (a[key] > b[key]) - (a[key] < b[key]);

let users = [{ name: "John", age: 20, surname: "Johnson" }, { name: "Pete", age: 18, surname: "Peterson" }, { name: "Ann", age: 19, surname: "Hathaway" }];

console.log(users.sort(withKey('name')));
console.log(users.sort(withKey('age')));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392