JS Built-ins
Algorithmsadvanced

Custom Sort with Comparator

πŸ“– Usage Example
function quickSort(arr) {
  if (arr.length <= 1) return arr;
  const pivot = arr[0];
  const left = arr.slice(1).filter(x => x <= pivot);
  const right = arr.slice(1).filter(x => x > pivot);
  return [...quickSort(left), pivot, ...quickSort(right)];
}

Quick sort picks a pivot and partitions the array into smaller and larger elements.

Custom Sort with Comparator

JavaScript's Array.prototype.sort() accepts a comparator function. A stable sort maintains the relative order of equal elements. The default sort is stable in modern engines.

Time Complexity: O(n log n) Space Complexity: O(n)

function sortByProperty(arr: {name: string, age: number}[], prop: string): {name: string, age: number}[] {
  // Sort using a custom comparator
}

const people = [{name: 'Alice', age: 30}, {name: 'Bob', age: 25}]
sortByProperty(people, 'age')
// [{name: 'Bob', age: 25}, {name: 'Alice', age: 30}]
πŸ’‘ Hints (3)
  • β€’ Use the spread operator to create a copy of the array.
  • β€’ The comparator function should return -1, 0, or 1.
  • β€’ Return -1 if a should come before b, 1 if after, 0 if equal.