Coding Challenge - #10: Sort By Property

Write a function sortBy(arr, key, order) that returns a new array of objects sorted by the given key in either 'asc' (ascending, default) or 'desc' (descending) order without mutating the original array. For example, sortBy([{age: 30}, {age: 20}], 'age', 'desc') should return [{age: 30}, {age: 20}].

function sortBy(arr, key, order = 'asc') {
  // Your code here
}

Rules:

  • Do not mutate the input array.
  • Handle numeric and string property values.
  • Default to ascending order when the order parameter is omitted.

Post your solution as a reply. Answer goes up in about a day.

1 Like

A simple approach is to copy the array first, then sort the copy:

function sortBy(arr, key, order = 'asc') {
  return [...arr].sort((a, b) => {
    const result = a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0;
    return order === 'desc' ? -result : result;
  });
}

This works for both numbers and strings, and [...] ensures the original array isn’t mutated.

Yo, that’s a solid solution! I lowkey always forget about localeCompare for strings, which can clean up that a[key] > b[key] logic a bit.

localeCompare is good for string sorting, yes. It handles nuances like accented characters and different language rules that simple comparisons miss.